c++ - 使用模板在 cpp 中映射类型
问题描述
我有一个来自外部库的函数模板,需要用户定义类型才能使用它。
template < int runtime_t >
typename ExtLib::apply<runtime_t>::type get_value(std::string) ;
要使用它,我需要指定用户定义的类型,例如:
get_value<ExtLib::pool_t::boolean_>("key_of_boolean_value");
get_value<ExtLib::pool_t::float_>("key_of_float_value");
我想包装这个“ExtLib”,以便将它从主程序中隐藏起来,这样我就可以将它与内置 cpp 类型一起使用:
bool val = get_value<bool>("key");
float val2 = get_value<float>("key2");
我试过使用地图,但没有任何成功。甚至可能吗?
解决方案
您可以通过类模板从标准类型映射到库类型:
template <typename T>
struct Convert;
template <>
struct Convert<bool>
{
static const int value = ExtLib::pool_t::boolean;
};
template <>
struct Convert<float>
{
static const int value = ExtLib::pool_t::float;
};
.. map other types
接着
template <typename T>
auto get_value(const std::string& key)
{
return get_value<Convert<T>::value>(key)
}
get_value
或者,您可以在自己的命名空间中定义一个函数模板,并重载或专门化它以使用库命名空间中具有相同名称的函数,例如。
// libadapter.h
namespace myns
{
template <typename T> T get_value(const string& key);
// specialize for bool, for ex.
template <bool>
bool get_value(const std::string& key)
{
return library::get_value<Extlib::pool_t::boolean>(key));
}
/* or
template <bool>
auto get_value(const std::string& key)
{
return static_cast<bool>(library::get_value<Extlib::pool_t::boolean>(key))
}
*/
// specialize for float
template <float>
float get_value(const std::string& key)
{
return library::get_value<Extlib::pool_t::float>(key);
}
// ... specialize for other types as well, if necccessary ...
}
然后在一些.cpp中:
#include "libadapter.h"
using myns::get_value;
... use get_value ...
推荐阅读
- android - 在 Appsflyer 中,“操作数”事件在 Android 设备中单击时不会更新。但是在模拟器中工作
- multithreading - 如何将隔离与整个类一起使用,而不仅仅是起点功能
- wpf - 带有图像的 WPF 材料设计菜单项
- bash - bash 用带空格的参数分配变量
- c# - 如何使用抽象工厂设计模式在 C# 中打开子窗口并绘制/绘制形状?
- c++ - 从分离线程停止主游戏循环的最佳方法
- python-3.x - 块缩进 - python
- java - 带有 Bash 抛出错误的 Git 多樱桃选择
- debugging - Common Lisp - 我的调试器出了什么问题?
- c# - 在 C# 中将用户输入转换为命令行