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

标签 c++ templates inheritance gcc template-inheritance

当我将模板函数作为基类的模板参数传递时,链接器提示它无法链接该函数:

#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/

相关文章:

c++ - GCC:我什么时候可以期望返回大型 C++ 对象是高效的?

C++ 执行类型检查但不编译文件

c++ - 函数特化/重载规则示例

c++ - 如何 tuple<Ts...>& base = t;在元组实现中工作

C++ 调用继承的构造函数

c++ - 在 C++ 中使用 Boost 正则表达式进入具有特定特征的方括号之间没有得到答案

C++ : How to bind inherited methods only to parent classes?

c++ - 模板规范问题

c# - 泛型继承......不起作用

C++ 继承 : Do I have to repeat parent attributes in derived classes?