我需要一个调度程序功能,如下所示
template<typename T>
T dispatcher() {
// if T is double
return _func_double();
// if T is int
return _func_int();
// if T is char*
return _func_char_pointer();
}
Run Code Online (Sandbox Code Playgroud)
并将使用如下
// some code that use above dispatcher
template<typename T1, typename T2, typename T3>
void do_multiple_thing(T1 *a1, T2 *a2, T2 *a3) {
*a1 = dispatcher<T1>();
*a2 = dispatcher<T2>();
*a3 = dispatcher<T3>();
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我怎么做到的吗?
PS
- 内置类型的解决方案才足够.
- 预处理和模板适用都是可以接受的.
如果你有支持C++ 17的编译器,那么这段代码应该可以工作:
template<typename T>
T dispatcher() {
// if T is double
if constexpr (std::is_same<T, double>::value)
return _func_double();
// if T is int
if constexpr (std::is_same<T, int>::value)
return _func_int();
// if T is char*
if constexpr (std::is_same<T, char*>::value)
return _func_char_pointer();
}
Run Code Online (Sandbox Code Playgroud)
否则,您将不得不进行模板特化,并为您想要的每个参数进行重载
//only needed for static assert
template<typename T>
struct always_false : std::false_type {};
template<typename T>
T dispatcher()
{
//to make sure that on type you didn't overload you will have exception
throw std::exception("This type was not overloaded")
//static assert that will provide compile time error
static_assert(always_false<T>::value , "You must specialize dispatcher for your type");
}
//or to get compile time error without static assert
template<typename T>
T dispatcher() = delete; //the simplest solution
template<>
double dispatcher<double>()
{
return _func_double();
}
//... and so on for all other functions
Run Code Online (Sandbox Code Playgroud)