tags:

views:

48

answers:

2

Hi,

I'm wondering what's the proper syntax for calling template method given as:

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;
};

I came up with sth like this:

print_ch printer('c');
printer.operator()<int>();

And it seems to work (GCC 4.5), but when I use it inside another templated method, e.g.:

struct printer {

    typedef int print_type;

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

};

Compilation fails with error: expected primary-expression before '>' token. Any idea to get it right? Thanks in advance.

+7  A: 

You have to tell the compiler explicitly that the operator() of the templated fnct is itself a template:

fnct.template operator()<print_type>();

If you don't specify this with the template keyword the compiler will assume that operator() is just a normal method, not a template.

sth
@sth exactly that, now it looks so obvious - thanks!
erjot
+2  A: 

Since T_functor is itself a template, the compiler (or parser) assumes to know nothing about it's members, so you have to explicetly tell it you are calling a template methode using:

        fnct.template operator()<print_type>();
Grizzly