我在下面的代码有一个奇怪的链接错误: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
那么问题出在哪里?
也许这是一个轻微错误的类型,就像一个const失踪?或者有涉及的命名空间...... –
你的“定义”是错误的,想想没有'enable_if'的东西应该是什么样子。 – juanchopanza