c++ - 模板成员函数调用—— "error: expected primary-expression before ' int'”

标签 c++ c++11

<分区>

我正在尝试测试下面的代码但出现编译错误:

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

构建命令:

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;
}

最佳答案

下一行是不正确的:

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?

关于c++ - 模板成员函数调用—— "error: expected primary-expression before ' int'”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37905120/

相关文章:

c++ - 使用 restrict 关键字摆脱函数的 "type qualifier"警告

c++ - 使用 extern 从 Haxe 访问 C++ 类

c++ - C++中放弃当前线程的时间片

c++ - 如何在编译时计算梅森数

c++ - 在 C++0x 中删除虚函数

c++ - 在 C++ 的二维数组中通过引用传递有问题

c++ - 使用 Visual Studio 2015 Win64 编译 MySQL Connector

c++ - icc版本13.0.0标志进行编译

c++ - 我如何在 C++ 中遍历集合?

c++ - 非阻塞 std::getline,如果没有输入则退出