我在以下代码中遇到奇怪的链接器错误:
代码使用类型特征为所有类型A<T>
提供部分模板特化,其中T
不是X
的子类型。
class X{};
#include <type_traits>
//Enabler for all types that are not a subtype of X
#define enabler(T) typename std::enable_if<!std::is_base_of<X, T>::value>::type
//A template (second param is only for enabling partial specializations)
template <typename T, typename = void>
struct A{};
//Partial template specialization for instances
//that do not use a T which is a subclass of X
template <typename T>
struct A<T, enabler(T)>{
static int foo(); //Declaration only!
};
//Definition of foo() for the partial specialization
template <typename T,enabler(T)>
static int foo(){
return 4;
}
int bar = A<int>::foo();
int main(){}
即使这只是一个文件,链接也会失败。问题似乎是foo()的非内联定义。一旦我内联它,一切正常。在实际代码中,由于循环依赖,我无法内联它。
错误如下:
/tmp/ccS7UIez.o: In function `__static_initialization_and_destruction_0(int, int)':
X.cpp:(.text+0x29): undefined reference to `A<int, void>::foo()'
collect2: ld returned 1 exit status
问题出在哪里?
答案 0 :(得分:2)
静态成员函数A<T, enabler(T)>::foo
的定义有语法错误,应该是:
template <typename T>
int A<T, enabler(T)>::foo(){
return 4;
}