I got a strange linker error on the following code:
The code uses type traits to provide a partial template specialization for all types A<T> where T is not a subtype of 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(){}
Even though this is only one file, linking fails. The problem seems to be the non-inline definition of foo(). Once I inline it, everything works fine. In the real code, I cannot inline it due to circular dependencies.
The error is the following:
/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
So where is the problem?
The definition of static member function
A<T, enabler(T)>::foohas syntax errors, should be :