2012-08-31 21 views
0

我在下面的代码有一个奇怪的链接错误:C++:调试C++模板链接器错误

代码使用类型的特征为各类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

也许这是一个轻微错误的类型,就像一个const失踪?或者有涉及的命名空间...... –

+0

你的“定义”是错误的,想想没有'enable_if'的东西应该是什么样子。 – juanchopanza

回答

2

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

template <typename T> 
int A<T, enabler(T)>::foo(){ 
    return 4; 
} 
+0

当我使用您的版本时,我收到以下编译器错误:'X.cpp:23:35:error:invalid use of incomplete type'struct A : :value>),void> :: type>' X.cpp:12:9:error:'struct A :: value),void> :: type>'' – gexicide

+0

抱歉修正了错字 –