另一个字符串文字,UDL 迷宫
Yet another string literal, UDL labyrinth
注意:这是MSVC,C++17问题。
免责声明:我知道这已经尝试过,是的,我试图找到相关的 SO 答案。
我可以对 UDL 进行编码,以实现在编译时将数字文字转换为std::array
:
// std::array{ '1','2','3' }
constexpr auto a_1 = 123_std_char_array;
// std::array{ '0','x','1','2' }
constexpr auto a_2 = 0x12_std_char_array;
// std::array{ '4'.'2','.','1','3' }
constexpr auto a_3 = 42.13_std_char_array;
这是我制作的 UDL:
template< char ... Chs >
inline constexpr decltype(auto) operator"" _std_char_array( )
{
// append ' '
return std::array { Chs..., char(0) } ;
}
惊人的,时髦的,现代的,等等,等等...但。
问题
如何编写 UDL 以允许此操作:
// std::array {'S','t','r','i','n','g'}
constexpr auto std_char_array_buff_ =
"String"_std_char_array ;
在 MSVC 中,请C++17。
忏悔录
我知道 UDL 要"捕获"字符串文字必须具有以下足迹:
inline auto operator"" _X( const char*, size_t);
我知道如何在编译时将字符串文字转换为 std::array。但没有 UDL。请看这里,获取灵感。
是的,我知道 C++20 将添加 UDL 模板,而 GCC、clang 现在还有其他东西。虽然我不明白这些对我有什么帮助。
最后,我知道我可以做到这一点:
constexpr auto string_view_ = "String"sv ;
不幸的是,这在 C++17 中似乎是不可能的。用户定义的字符串文本只能匹配每个 [lex.ext]/5 的operator""X(str, len)
。 然后,len
是函数参数,函数参数不能转换为模板参数。 就像你不能这样做一样:
template <int N>
struct S {};
constexpr auto f(int n)
{
return S<n>{}; // no, n is not guaranteed to be known at compile time
}
"foo"sv
工作是因为 size 不是std::basic_string_view
的模板参数,而是一个"运行时"属性,它恰好受益于constexpr
。 您无法使用std::array
执行此操作,因为大小是std::array
的模板参数。
make_array
工作,因为它不是文字运算符,因此它可以将大小作为模板参数而不是函数参数。 然后,它可以将模板参数传递给std::array
。 文字运算符无法做到这一点。
在 C++20 中,我认为我们可以使用这样的包装器类型:
template <std::size_t N>
struct helper {
std::array<char, N> string;
template <std::size_t... Is>
constexpr helper(const char (&str)[N + 1], std::index_sequence<Is...>)
:string{str[Is]...}
{
}
constexpr helper(const char (&str)[N + 1])
:helper{str, std::make_index_sequence<N>{}}
{
}
};
template <std::size_t N>
helper(const char (&str)[N]) -> helper<N - 1>;
然后使用字符串文本运算符模板:
template <helper str> // placeholder type for deduction
constexpr auto operator""_S()
{
return str.string;
}
static_assert("foo"_S == std::array{'f', 'o', 'o'});
不过C++20还没有最终确定,所以我不能肯定地说。
- 在迷宫c++中查找路径是否存在
- 用单元格表示迷宫
- 在函数范围之外的标头中使用 UDL
- 迷宫游戏 c++ 41 x 41 数组
- 另一个字符串文字,UDL 迷宫
- 用于在C++中绘制生成的迷宫的简单框架
- 通过迷宫求解程序回溯逻辑错误
- 迷宫生成矢量分割故障
- 使用C 中的递归对迷宫进行回溯
- 递归地查找通过迷宫 c++ 的路径
- 从TXT文件加载迷宫
- 找出迷宫求解器的最佳解决方案,并具有动画输出
- 迷宫构造函数问题 [线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)]
- 为什么非下划线名称保留给 UDL 的实现,而不是相反
- 迷宫生成-递归除法(它是如何工作的?)
- 3D 迷宫递归方法 - C++
- 如何在BFS算法中计算移动?(迷宫中的最短路径)
- 如何确保迷宫总是有一个有效的路径C++
- C 2D阵列迷宫导航
- 需要帮助在二维数组c++中实现迷宫