2012-08-31 19 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

抱歉修正了錯字 –