boost :: mpl :: type和char字符串的映射

时间:2015-09-27 06:50:05

标签: c++ boost boost-mpl

类似于

typedef boost::mpl::map<
      pair<int,"int">
    , pair<long,"long">
    , pair<bool,"bool">
    > m;

可能?如果没有,有哪些替代方案?

1 个答案:

答案 0 :(得分:2)

如果你可以使用C ++ 14编译器(目前只有Clang&gt; = 3.5),你可以使用Boost.Hana

#include <boost/hana.hpp>
namespace hana = boost::hana;

auto m = hana::make_map(
    hana::make_pair(hana::type_c<int>, BOOST_HANA_STRING("int")),
    hana::make_pair(hana::type_c<long>, BOOST_HANA_STRING("long")),
    hana::make_pair(hana::type_c<bool>, BOOST_HANA_STRING("bool"))
);

// These assertions are done at compile-time
BOOST_HANA_CONSTANT_ASSERT(m[hana::type_c<int>] == BOOST_HANA_STRING("int"));
BOOST_HANA_CONSTANT_ASSERT(m[hana::type_c<long>] == BOOST_HANA_STRING("long"));
BOOST_HANA_CONSTANT_ASSERT(m[hana::type_c<bool>] == BOOST_HANA_STRING("bool"));

如果您还愿意使用Clang和GCC支持的非标准GNU扩展(至少),您甚至可以执行以下操作并删除丑陋的BOOST_HANA_STRING宏:

#define BOOST_HANA_CONFIG_ENABLE_STRING_UDL

#include <boost/hana.hpp>
namespace hana = boost::hana;
using namespace hana::literals;

constexpr auto m = hana::make_map(
    hana::make_pair(hana::type_c<int>, "int"_s),
    hana::make_pair(hana::type_c<long>, "long"_s),
    hana::make_pair(hana::type_c<bool>, "bool"_s)
);

static_assert(m[hana::type_c<int>] == "int"_s, "");
static_assert(m[hana::type_c<long>] == "long"_s, "");
static_assert(m[hana::type_c<bool>] == "bool"_s, "");