模板方法未实例化
Template method is not instantiated
为什么我在这个程序(使用gcc 4.6.2)上出现链接错误:
#include <iostream>
// prints something;
// the template doesn't add anything
template <typename T>
struct Printer
{
void print()
{
std::cout << "Printer::print" << std::endl;
}
};
// this is an actual template
// calls the method indicated by the second template argument
// belonging to the class indicated by the first template argument
template < typename U, void(U::*func)()>
struct Caller
{
void call(U obj)
{
(obj.*func)();
}
};
// just a wrapper
template<typename V>
struct Wrapper
{
void call_caller_on_printer()
{
Printer<int> a_printer;
Caller<Printer<int>, &Printer<int>::print> caller;
caller.call(a_printer);
}
};
int main()
{
Wrapper<int> the_wrapper;
the_wrapper.call_caller_on_printer();
return 0;
}
链接器抱怨Printer::print是一个未定义的引用。但是,如果您使Wrapper成为一个非模板(该模板没有在其中添加任何内容),它就会起作用。Printer的打印方法似乎没有实例化。为什么?
我在GCC 4.5.1上遇到了一个类似的问题(是的,它看起来确实像一个回归)。
在我的例子中,它有助于显式地将指针强制转换为所需的类型,以使GCC 4.5.1接受此代码。试着在这里做同样的事情。即
Caller<Printer<int>, static_cast<void (Printer<int>::*)()>(&Printer<int>::print)> caller;
(未经测试;顺便说一句,这里的强制转换在语法上有效吗?否则,元函数可能会有所帮助。)
相关文章:
- 如何使用非默认构造函数实例化模板化类
- 无法使用迭代器标记调度实例化模板
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- 实例化模板时,我是否必须显式显示参数包中的类型?
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 如何同时别名和实例化模板函数?
- 无法显式实例化模板化类
- 您能否实例化模板的非专用版本并在专用化中继承它?
- 初始值设定项列表是否足够静态以允许实例化模板?
- 尝试实例化模板类的对象时出现"No Matching Constructor"错误
- 从模板基类派生是否在派生类声明的点实例化模板
- 实例化模板参数的参数包
- 使用 SFINAE 有选择地实例化模板的成员函数
- 在预编译标头中实例化模板会缩短编译时间吗?
- 找不到使用 bitset 实例化模板函数的有效方法
- 使用动态布尔变量实例化模板
- 在C 中,当我对其进行专业化时会实例化模板
- 如何在尝试为某些非类型值实例化模板子类方法时产生编译器错误
- 如何使用swig实例化模板类的模板方法
- 如何用具有特定方法的类实例化C++模板