gpt4 book ai didi

c++ - 如何创建 boost::hana::map 键是编译时字符串(C++14)?

转载 作者:搜寻专家 更新时间:2023-10-31 02:05:49 24 4
gpt4 key购买 nike

我在 boost.hana 邮件列表中看到了以下无法编译的示例:

#include <boost/hana.hpp>
#include <string>
namespace hana = boost::hana;
int main(int argc, char **argv) {

constexpr auto m1 = hana::make_map(
hana::make_pair("key1"_s, hana::type_c<std::string>),
hana::make_pair("key2"_s, hana::type_c<std::string>)
);
}

我在 GCC 7.3.0 -std=c++14 上收到以下错误:

error: unable to find string literal operator ‘operator""_s’ with ‘const char [5]’, ‘long unsigned int’ arguments
hana::make_pair("key1"_s, hana::type_c<std::string>),
^~~~~~~~

顺便问一下,字符串文字的 «_s» 后缀是什么?

最佳答案

Boost.Hana 的编译时字符串文字运算符 _s正在使用的是 gcc 扩展,必须通过定义 BOOST_HANA_CONFIG_ENABLE_STRING_UDL 来启用。

您还必须从 boost::hana::literals 将运算符导入当前命名空间。

或者,有一个宏BOOST_HANA_STRING可以使用,但它使用 lambda 并且在 C++14 中不能是 constexpr。

虽然尚未最终确定,但 C++20 可能会将此运算符以及字符串文字作为模板参数,这令人兴奋。 ( here )

这是一个完整的例子:

#define BOOST_HANA_CONFIG_ENABLE_STRING_UDL
#include <boost/hana.hpp>

namespace hana = boost::hana;
using namespace hana::literals;

int main() {
constexpr auto m1 = hana::make_map(
hana::make_pair("key1"_s, hana::type_c<void>),
hana::make_pair("key2"_s, hana::type_c<void>)
);

constexpr auto m3 = hana::make_map(
hana::make_pair(hana::string<'k','e','y','1'>{}, hana::type_c<void>),
hana::make_pair(hana::string<'k','e','y','2'>{}, hana::type_c<void>)
);

// not constexpr until C++17
auto m2 = hana::make_map(
hana::make_pair(BOOST_HANA_STRING("key1"), hana::type_c<void>),
hana::make_pair(BOOST_HANA_STRING("key2"), hana::type_c<void>)
);
}

关于c++ - 如何创建 boost::hana::map 键是编译时字符串(C++14)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51261788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com