模板方法未实例化
为什么我在这个程序上遇到链接错误(使用 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的打印方法似乎没有被实例化。这是为什么?
Why am I getting link errors on this program (with 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;
}
The linker complains that Printer::print is an undefined reference. However, if you make Wrapper a non-template (the template doesn't add anything there), it works. The print method of Printer does not seem to be instantiated. Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
我在 GCC 4.5.1 上遇到了一个看起来类似的问题(是的,它看起来确实像回归)。
就我而言,它有助于将指针显式转换为所需类型,以使 GCC 4.5.1 吞下此代码。尝试在这里做同样的事情。即
(未经测试;顺便说一句,这里的强制转换在语法上是否有效?否则元函数可能会有所帮助。)
I’ve had a problem that looks similar on GCC 4.5.1 (and yes, it does look like a regression).
In my case, it helped to explicitly cast the pointer to the desired type to make GCC 4.5.1 swallow this code. Try doing the same here. I.e.
(Untested; incidentally, is a cast even syntactically valid here? Otherwise a metafunction might help.)