Difference between member functions for a template class defined inside and outside of the class

后端 未结 3 1285
太阳男子
太阳男子 2021-02-14 11:43

Is there a difference between defining member functions for a template class inside the class declaration versus outside?

Defined inside:

template 

        
3条回答
  •  花落未央
    2021-02-14 12:26

    Yes, the exact same is true for template classes.

    The reason why method definitions for template classes are usually preferred to be inline is that with templates, the entire definition must be visible when the template is instantiated.

    So if you put the function definition in some separate .cpp file, you'll get a linker error. The only general solution is to make the function inline, either by defining it inside the class or outside with the inline keyword. but in either cases, it must be visible anywhere the function is called, which means it must typically be in the same header as the class definition.

提交回复
热议问题