次のコードで奇妙なリンカ エラーが発生しました。
コードは型特性を使用して、 が のサブタイプ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(){}
これは 1 つのファイルだけですが、リンクは失敗します。問題は、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
では、どこに問題があるのでしょうか。