Are pure virtual methods allowed within a template class?

前端 未结 4 677
暗喜
暗喜 2020-12-23 16:47

Once before, I was certain that you couldn\'t do this, but the other day I was playing around with some code and it seemed to compile and work. I just want to verify that I

4条回答
  •  醉梦人生
    2020-12-23 16:48

    Think about what a template class is -- it is not a class itself, but a template the compiler can use to create classes.

    As such, there's no reason you can't include a virtual function (pure or otherwise) in the template class definition, because that, in and of itself, does not generate any code, including the virtual table.

    When we actually instantiate the template class, e.g. DataSource, then the compiler only needs to build the virtual table for that one selected type, so it's not any different than a (pure or otherwise) virtual function for a non-templated class.

提交回复
热议问题