调用模板化方法的语法

erj*_*jot 6 c++ templates

我想知道调用模板方法的正确语法是什么:

struct print_ch {
    print_ch(char const& ch) : m_ch(ch) { }
    ~print_ch() { }
    template<typename T>
    void operator()() {
        std::cout << static_cast<T>(m_ch) << std::endl;
    }
    private:
    char m_ch;
};
Run Code Online (Sandbox Code Playgroud)

我想出了这样的事:

print_ch printer('c');
printer.operator()<int>();
Run Code Online (Sandbox Code Playgroud)

它似乎工作(GCC 4.5),但当我在另一个模板化方法中使用它时,例如:

struct printer {

    typedef int print_type;

    template<typename T_functor>
    static void print(T_functor& fnct) {
        fnct.operator()<print_type>();
    }

};
Run Code Online (Sandbox Code Playgroud)

编译失败error: expected primary-expression before '>' token.任何想法让它正确吗?提前致谢.

sth*_*sth 8

您必须明确告诉编译器operator()模板化fnct的本身是一个模板:

fnct.template operator()<print_type>();
Run Code Online (Sandbox Code Playgroud)

如果不使用template关键字指定此项,编译器将假定这operator()只是一种常规方法,而不是模板.