Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for calling templated method

Tags:

c++

templates

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.

like image 341
erjot Avatar asked Oct 22 '10 19:10

erjot


2 Answers

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.

like image 84
sth Avatar answered Sep 28 '22 07:09

sth


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>();
like image 43
Grizzly Avatar answered Sep 28 '22 06:09

Grizzly