关于C++:在>:之前的预期主表达式

expected primary-expression before ‘>’ token

本问题已经有最佳答案,请猛点这里访问。

我有这样一个代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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: error: expected primary-expression before ‘>’ token
int protoId = helper.GetProtocolId();

test.cc:23:58: error: expected primary-expression before ‘)’ token

我做错什么了?int protoid=helper.getprotocolid();


您只需将template关键字放在后面,表示它跟踪一个模板:

1
2
int protoId = helper.template GetProtocolId<PROTOCOL_CLASS>();
                     ^^^^^^^^