这个程序(用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;
}
链接器抱怨打印机打印::是一个未定义的参考。但是,如果您将Wrapper设置为非模板(该模板不会在其中添加任何内容),则它可以工作。打印机的打印方法似乎没有被实例化。这是为什么?
FWIW,适用于[GCC 4.3.4(http://ideone.com/pR7y6 )和MSVC10,在[GCC 4.5.1](http://ideone.com/6VDTp)上失败。看起来像是对我的回归。 – ildjarn 2012-02-15 23:20:56