通常,在头文件中声明一个成员函数,并使用源文件来实现它。我对原因的理解是函数实现将只驻留在一个翻译单元中,只会链接到其他单元(没有重复代码),它还允许分离接口(interface)和实现,并且不需要转发声明函数相互依赖。
但是,模板中的成员函数依赖于模板参数,如果实现放在源文件中则无法得知。然而,仍然可以在类之外定义此类函数,但它的主要论点不再适用。
那么,哪个更好呢?
template <class T>
class A
{
T m()
{
return T();
}
};
或
template <class T>
class A
{
T m();
};
template <class T>
T A::m()
{
return T();
}
如果是inline T A::m()
,这两段代码是等价的,但是没有它有什么区别吗?如果函数是虚拟的怎么办?这只是编码风格的问题,还是具有不同的语义?如果函数足够大,是否会防止重复代码,或者编译器是否足够聪明,不会在没有任何好处的情况下内联它?
最佳答案
These two pieces of code would be equivalent if it was
inline T A::m()
, but is there any difference without it?
不适用于模板,成员函数是隐式的 inline
,对于类定义的内部和外部。
What if the function is virtual?
没有区别。
Is it just a matter of coding style, or does it have different semantics?
主要是文体。但是,它会影响名称查找的工作方式。所以如果我们稍微修改类定义
template <class T>
class A
{
using foo = T;
foo m();
};
我们无法将外部成员定义为
template <class T>
foo A<T>::m()
{
return T();
}
自从查找 foo
直到资格 A<T>::
之后才在类定义中发生.我们需要要么完全符合 foo
本身,就像这样typename A<T>::foo
.或者可能使用尾随返回类型。
If the function is large enough, will it prevent duplicate code, or is the compiler smart enough not to inline it if it won't bring any benefits?
这两种风格都不应该对它产生负面影响或正面影响。两者都受实现质量问题的影响。但当然,不同的实现可能具有不同的品质。
关于c++ - 模板类中的函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48366569/