0

我在以下代码中遇到了一个奇怪的链接器错误:

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

那么问题出在哪里?

4

1 回答 1

2

静态成员函数的定义A<T, enabler(T)>::foo有语法错误,应该是:

template <typename T>
int A<T, enabler(T)>::foo(){
    return 4;
}
于 2012-08-31T13:57:13.980 回答