c++ - 模板处理程序方法调度程序

标签 c++ templates c++11

这是 this 的延续问题。

我有不同的模板方法,每个方法用于不同类型的消息,使用非类型模板参数和模板特化:

namespace Handlers {

enum MSG_TYPES {
    MSG1,
    MSG2

};

template<MSG_TYPES>
void handle_message() {
    // Default handler : not defined type
}


template<>
void handle_message<MSG1>() {
    cout << "Handle 1";
}

template<>
void handle_message<MSG2>() {
    cout << "Handle 2";
}

现在,我想要一些其他方法来分派(dispatch)给正确的处理程序。有点像

template<typename T>
void handle(T t) {
    try {
        handle_message<T>();
    } catch(...) {

    }
}

可以这样调用

int i = 0;
Handlers::handle(static_cast<Handlers::MSG_TYPES>(i));

那么,这个调度器是如何实现的呢?

PS:之前的代码在 handle_message<T>(); 上失败了因为

note: template argument deduction/substitution failed:

不应该调用默认处理程序吗?

最佳答案

你的方法应该是这样的:

void handle(MSG_TYPES type) {
    switch (type) {
        case MSG1: handle_message<MSG1>();
        case MSG2: handle_message<MSG2>();
    }
}

关于c++ - 模板处理程序方法调度程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37262977/

相关文章:

c++ - 需要澄清 C++ 模板格式

c++ - 创建模板内部 lambda 函数?

c++ - 从参数包中获取 typedef

c++ - 参数类型自动推导和匿名 lambda 函数

c++ - std::unordered_map 和重复键

c - 具有正确文件长度和缓冲区分配的 fread 段错误

c++ - 自定义 malloc 实现

c++ - 向使用 C++ 中的链表实现的有向图(邻接表)添加边

c++ - 如何使用cout以全精度打印 double 值?

c++ - 按索引访问 map 值