使用模板在 cpp 中映射类型

时间:2021-02-04 11:18:38

标签: c++ templates types

我有一个来自外部库的函数模板,需要用户定义类型才能使用它。

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");

我尝试过使用地图,但没有成功。甚至有可能吗?

2 个答案:

答案 0 :(得分:1)

您可以通过类模板从标准类型映射到 lib 类型:

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 ... 

答案 1 :(得分:0)

感谢@StPiere,我可以回答我自己的问题:

std::undordered_map<std::type_index, int> map_types = {
{std::type_index(typeid(bool)), ExtLib::pool_t::boolean_},
{std::type_index(typeid(long)), ExtLib::pool_t::long_},
{std::type_index(typeid(float)), ExtLib::pool_t::float_},
{std::type_index(typeid(double)), ExtLib::pool_t::double_}
}

template <typename T>
T getValue(std::string key) {
const int TT = map_types[std::type_index(typeid(T))]
return get_value<TT>(key);
};
相关问题