0

当编译器认为代码是本地链接或内联时,如何实现类静态函数的外部链接?

考虑三个文件:

特征.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 外部链接,同时仍在类定义中编写函数?

4

1 回答 1

0

I think you need to decide whether to have external linkage and define out of line or keep it inline and effectively just have internal linkage. Is there a reason not to define your Traits<int> in a header? Note that the full specialization is no longer a template, so there is really no difference to how it is handled versus a non-templated function.

Edited: Tried this in VS2010, and it may still not suit, but you could put code in traitsimp.cpp that takes the address of the method:

auto getAddress = &Traits<int>::InlineFunction;

This forces the method to get an address. I'm a bit rusty on whether this behaviour would be standard or not.

于 2013-03-13T04:38:30.913 回答