如果我有一个 header foo.h,我将其包含在我的整个项目中,当它只包含以下内容时它似乎工作正常:
template<typename T>
void foo(const T param) {
cout << param << endl;
}
但是当我向 foo.h 添加一个特化时,我得到一个定义规则 (ODR) 错误:
template<>
void foo(const bool param) {
cout << param << endl;
}
显然,我可以通过内联
特化来解决这个问题。我的问题是,为什么我需要这样做?如果模板不违反 ODR,为什么要专门化?
最佳答案
显式特化不是隐式内联的。它必须显式内联。
An explicit specialization of a function or variable template is inline only if it is declared with the inline specifier or defined as deleted, and independently of whether its function or variable template is inline. [ Example:
template<class T> void f(T) { /* ... */ } template<class T> inline T g(T) { /* ... */ } template<> inline void f<>(int) { /* ... */ } // OK: inline template<> int g<>(int) { /* ... */ } // OK: not inline
— end example ]
所以你必须这样做,因为标准规定你必须这样做。
关于c++ - 内联模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51987423/