c++ - 内置类型的基于 C++ 类型的分派
问题描述
我需要一个调度程序功能,如下所示
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();
}
并将像下面一样使用
// 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>();
}
你能告诉我如何实现吗?
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();
}
否则,您将不得不进行模板专业化,并为您想要的每个参数进行重载
//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
推荐阅读
- vba - VBA Sumifs 将结果粘贴为值
- java - JPQL 中具有类型列表属性的投影
- sql - 100 个逗号分隔的随机计数器位置值求和并显示过去 60 分钟的统计数据
- spring - Guava(Spring)中过期后如何刷新缓存中的键和值
- python - Python - matplotlib - 如何从方程中绘制平面?
- c++ - 适用于 Visual Studio 的混合
- laravel - laravel Voyager 多语言如何在需要的语言环境中显示带有翻译的项目
- rest - 使用 JavaDSL 配置到外部 URL 的 apache-camel 路由
- c# - 将数据从 GridView 保存到数据库时输入字符串格式不正确
- c# - 如何在迭代中同时中断和继续?