在类内部和外部定义的模板类的成员函数之间的差异 [英] Difference between member functions for a template class defined inside and outside of the class

查看:256
本文介绍了在类内部和外部定义的模板类的成员函数之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类声明中为模板类定义成员函数和外部是否有区别?



定义在内部:

  template< typename T> 
class A
{
public:
void method()
{
// ...
}
}

定义在外部:

  template< typename T> 
class B
{
public:
void method();
};

template< typename T>
void B< T> :: method()
{
// ...
}

对于非模板类,这是内联和非内联方法之间的区别。这是否也适用于模板类?



我的大多数同事的默认是在类中提供定义,但我一直喜欢在类外面的定义。


$ b h2_lin>解决方案

是的,模板类也是如此。



模板类的方法定义通常是首选



因此,如果你把函数定义放在一些单独的.cpp文件中,你就可以看到将得到链接器错误。
唯一的通用解决方案是使函数内联,通过在类中定义它或在外部使用 inline 关键字。但在任何情况下,它必须在函数被调用的任何地方可见,这意味着它通常必须与类定义位于同一个头。


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

Defined inside:

template <typename T>
class A
{
public:
    void method()
    {
        //...
    }
};

Defined outside:

template <typename T>
class B
{
public:
    void method();
};

template <typename T>
void B<T>::method()
{
    //...
}

For non-template classes, this is the difference between inlined and non-inlined methods. Is this also true for template classes?

The default for most of my colleagues is to provide definitions inside the class, but I've always preferred definitions outside the class. Is my preference justified?

Edit: Please assume all the above code is provided in the header file for the class.

解决方案

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.

这篇关于在类内部和外部定义的模板类的成员函数之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆