c++ - boost::mpl::map 类型和 char 字符串

标签 c++ boost boost-mpl

类似于下面的内容

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

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

最佳答案

如果你可以使用 C++14 编译器(目前只有 Clang >= 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, "");

关于c++ - boost::mpl::map 类型和 char 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805328/

相关文章:

c++ - boost fusion/MPL : convert type from sequence to sequence of equivalent any_range's

c++ - 如何使用 Boost MPL 在函数中拥有多个返回点?

c++ - 在整个范围内使用 vector::erase

c++ - ##(双哈希)在预处理器指令中做了什么?

c++ - 在单头文件、静态库和共享库之间链接 boost 库的哪种用法变体更好?

c++ - boost::asio::io_service::run 在没有工作时不返回

c++ - 使用 boost mpl pop_front

c++ - 如何将 boost::shared_ptr<T> 后面的完整对象深度复制到指向新位置的 shared_ptr?

c++ - 删除字符指针得到堆错误

c++ - boost::program_options:带有固定和可变标记的参数?