1

I am trying to test below code but getting compile error:

TemplateTest.cpp:44:13: error:expected primary-expression before 'int'
        h_.handle<int>(i);

build command:

g++ -c -std=c++11 -g -O2 -Wall -Werror TemplateTest.cpp -o TemplateTest.o

#include <iostream>
using namespace std;

enum PROTOCOL {
  PROTO_A,
  PROTO_B
};

// ----- HandlerClass -------
template <PROTOCOL protocol>
class Handler {
public:
    template <class TMsg>
    bool handle(const TMsg&) {
        return false;
    }
};

template <>
template <class TMsg>
bool Handler<PROTO_A>::handle(const TMsg&) {
    cout << "PROTO_A handler" << endl;
    return true;
}

template <>
template <class TMsg>
bool Handler<PROTO_B>::handle(const TMsg&) {
    cout << "PROTO_B handler" << endl;
    return true;
}

// ----- DataClass ------
template <PROTOCOL protocol>
struct Data {
    typedef Handler<protocol> H; //select appropriate handler
    H h_;
    int i;
    Data() : i() {}

    void f() {
            h_.handle<int>(i); //***** <- getting error here
    }
};

int main () {
    Data<PROTO_A> b;
    b.f();
    return 0;
}
ashwin929
  • 43
  • 4
  • inside a `template` to call another template one need `template` clause. In your particular example: `h_.template handle(i);` – W.F. Jun 19 '16 at 07:57
  • THANKS W.F. This worked. :) . but Why? could you point me to some related references – ashwin929 Jun 19 '16 at 07:59
  • actually this is due to the fact compiler cannot establish if the "<" character is the less operator or if it is a start of a template invocation... see related: http://stackoverflow.com/questions/7397934/calling-template-function-within-template-class – W.F. Jun 19 '16 at 08:04

1 Answers1

2

Below line is incorrect:

h_.handle<int>(i);

Since h_ is an instance of a template class Handler<PROTOCOL>.

Change it to:

h_.template handle<int>(i);

You should checkout answer to the below SO question:

Where and why do I have to put the "template" and "typename" keywords?

Community
  • 1
  • 1
Arunmu
  • 6,837
  • 1
  • 24
  • 46