当编译器认为代码是本地链接或内联时,如何实现类静态函数的外部链接?
考虑三个文件:
特征.h:
template <typename T>
struct Traits
{
static int InlineFunction(T);
static int Function(T);
};
traitsimp.cpp:
#include "traits.h"
template <>
struct Traits<int>
{
static int InlineFunction(int) { return 42; }
static int Function(int);
};
int Traits<int>::Function(int i) { return i; }
主.cpp:
#include "traits.h"
int main()
{
int result = Traits<int>::Function(5);
result = Traits<int>::InlineFunction(result);
return 0;
}
编译时收到:
$ g++ traitsimp.cpp main.cpp -o traitstest
/tmp/cc6taAop.o: In function `main':
main.cpp:(.text+0x1b): undefined reference to `Traits<int>::InlineFunction(int)'
collect2: ld returned 1 exit status
如何说服编译器提供 InlineFunction 外部链接,同时仍在类定义中编写函数?