另一个字符串文字,UDL 迷宫

Yet another string literal, UDL labyrinth

本文关键字:UDL 迷宫 文字 字符串 另一个      更新时间:2023-10-16

注意:这是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还没有最终确定,所以我不能肯定地说。