当我编写一个简单的(非模板)类时,如果函数实现是"正确"提供的,它会自动被视为inline
.
class A {
void InlinedFunction() { int a = 0; }
// ^^^^ the same as 'inline void InlinedFunction'
}
Run Code Online (Sandbox Code Playgroud)
在谈论基于模板的类时,这条规则怎么样?
template <typename T> class B {
void DontKnowFunction() { T a = 0; }
// Will this function be treated as inline when the compiler
// instantiates the template?
};
Run Code Online (Sandbox Code Playgroud)
此外,该inline
规则如何应用于非嵌套模板函数,例如
template <typename T> void B::DontKnowFunction() { T a = 0; }
template <typename T> inline void B::DontKnowFunction() { T a = 0; } …
Run Code Online (Sandbox Code Playgroud) 我有一个模板类,看起来像这样:
template<class T> class C
{
void A();
void B();
// Other stuff
};
template<class T> void C<T>::A() { /* something */ }
template<class T> void C<T>::B() { /* something */ }
Run Code Online (Sandbox Code Playgroud)
我想要的是仅A
在保留默认值B
和"其他内容"时提供显式特化.
到目前为止我尝试过的是
class D { };
template<> void C<D>::A() { /*...*/ } // Gives a link error: multiple definition
Run Code Online (Sandbox Code Playgroud)
我尝试过的每个其他变体都会因解析错误而失败.
最初的问题是显式特化是在头文件中,因此它被转储到几个目标文件中并弄乱了链接(为什么链接器没有注意到符号的所有实例都是相同的只是闭嘴?)
解决方案最终是将显式特化从头文件移动到代码文件.但是为了使头文件的其他用户不是默认版本的实例,我需要将原型放回头部.然后为了让GCC实际生成显式特化,我需要在代码文件中放置一个正确类型的虚拟变量.