模板方法未实例化

Template method is not instantiated

本文关键字:实例化 模板方法      更新时间:2023-10-16

为什么我在这个程序(使用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;

(未经测试;顺便说一句,这里的强制转换在语法上有效吗?否则,元函数可能会有所帮助。)