我正在尝试测试下面的代码但是收到编译错误:
TemplateTest.cpp:44:13:错误:在'int'之前预期的primary-expression
h_.handle< INT>(ⅰ);
构建命令:
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;
}
答案 0 :(得分:2)
以下行不正确:
h_.handle<int>(i);
由于h_
是模板类Handler<PROTOCOL>
的实例。
将其更改为:
h_.template handle<int>(i);
你应该检查以下SO问题的答案:
Where and why do I have to put the "template" and "typename" keywords?