这是 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/