当我将模板函数作为基类的模板参数传递时,链接器提示它无法链接该函数:
#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
如果我注释掉特化,那么代码会按预期编译和链接。另外,如果我从 Base<identity<Val> >
继承而不是 Base<identity<10> >
,代码按我的预期工作。
在这里试试:http://coliru.stacked-crooked.com/a/9fd1c3aae847aaf7
我错过了什么?
最佳答案
问题似乎是 gcc 错误:代码编译并与 clang、icc 和 EDG 前端链接。一个不改变任何用途的潜在解决方法是使用类模板 identity
而不是函数:
template<int I>
struct identity {
operator int() { return I; }
};
template<typename fn>
class Base {
public:
int f() {
return fn();
}
};
关于c++ - 错误消息 "undefined reference to template function passed as template parameter",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41399049/