我有一个代码:
class Client2ServerProtocol {
};
class ProtocolHelper {
public:
template<class ProtocolClass>
int GetProtocolId() {
return -1;
}
};
template<> inline int
ProtocolHelper::GetProtocolId<Client2ServerProtocol>() {
return 1;
}
template<typename PROTOCOL_HELPER>
class Dispatcher {
public:
template<typename PROTOCOL_CLASS>
void Subscribe(int msgId) {
int protoId = helper.GetProtocolId<PROTOCOL_CLASS>();
printf("Subscribe protoId %d, msgId %d", protoId, msgId);
}
PROTOCOL_HELPER helper;
};
int main() {
Dispatcher<ProtocolHelper> dispatcher;
dispatcher.Subscribe<Client2ServerProtocol>(1);
return 0;
}
它在MSVC下成功编译(和工作),但是gcc抱怨语法无效:
test.cc:23:56:错误:在'&gt;'标记之前预期的primary-expression int protoId = helper.GetProtocolId();
test.cc:23:58:错误:在')'标记之前预期的主要表达式
我做错了什么? int protoId = helper.GetProtocolId();
答案 0 :(得分:10)
您只需要使用template
关键字来表示它会跟进模板:
int protoId = helper.template GetProtocolId<PROTOCOL_CLASS>();
^^^^^^^^