错误消息 "undefined reference to template function passed as template parameter"

Error message "undefined reference to template function passed as template parameter"

当我将模板函数作为基 class 的模板参数传递时,linker 抱怨它不能 link 函数:

#include <stdio.h>

template<int I> inline int identity() {return I;}
//template<> inline int identity<10>() {return 20;}

template<int (*fn)()>
class Base {
public:
    int f() {
        return fn();
    }
};

template<int Val>
class Derived : public Base<identity<10> > {
public:
    int f2() {
        return f();
    }
};

int main(int argc, char **argv) {
    Derived<10> o;
    printf("result: %d\n", o.f2());
    return 0;
}

结果:

$ g++ -o test2 test2.cpp && ./test2
/tmp/ccahIuzY.o: In function `Base<&(int identity<10>())>::f()':
test2.cpp:(.text._ZN4BaseIXadL_Z8identityILi10EEivEEE1fEv[_ZN4BaseIXadL_Z8identityILi10EEivEEE1fEv]+0xd): undefined reference to `int identity<10>()'
collect2: error: ld returned 1 exit status

如果我注释掉专业化,那么代码会按预期进行编译和 links。此外,如果我从 Base<identity<Val> > 而不是 Base<identity<10> > 继承,代码将按我预期的方式工作。

在这里试试:http://coliru.stacked-crooked.com/a/9fd1c3aae847aaf7

我错过了什么?

将其提取到 typedef 中使其编译,即

typedef Base< identity<10> > base10;

我不太清楚为什么在 class 定义中直接这样做是行不通的。

http://coliru.stacked-crooked.com/a/f00b4f4d1c43c2b0

问题似乎是 gcc 错误:代码编译并与 clang、icc 和 EDG 前端链接。不改变任何用途的潜在解决方法是使用 class 模板 identity 而不是函数:

template<int I>
struct identity {
    operator int() { return I; }
};

template<typename fn>
class Base {
public:
    int f() {
        return fn();
    }
};