从c++11中用户定义的文字返回std::数组

returning a std::array from a user defined literal in c++11

本文关键字:返回 std 文字 数组 c++11 用户 定义      更新时间:2023-10-16

我刚刚安装了gcc-4.8.1,当我意识到我可以执行-std=c++1y并获得多行constexpr时,我非常兴奋。我很想知道,到底有没有办法让它发挥作用?

#include <array>
constexpr auto operator "" _a1 (const char* text, const size_t size) -> std::array<char,size> {
    std::array<char,size>() blah;
    std::strncpy(blah.data(), test, size);
    // do some stuff to blah at compile time
    return blah;
}

int main() {
    auto blah = "hello world"_a2;
}

但我得到了一个很大的可怕:

$ g++ test.cpp -std=gnu++1y -Wall -Werror -Wextra -Weffc++ -pedantic
test.cpp:3:100: error: use of parameter ‘size’ outside function body
 constexpr auto operator "" _a1 (const char* text, const size_t size) -> std::array<char,size> {
                                                                                                    ^
test.cpp:3:100: error: use of parameter ‘size’ outside function body
test.cpp:3:100: error: use of parameter ‘size’ outside function body
test.cpp:3:104: error: template argument 2 is invalid
 constexpr auto operator "" _a1 (const char* text, const size_t size) -> std::array<char,size> {
                                                                                                        ^
test.cpp: In function ‘int main()’:
test.cpp:26:17: error: unable to find string literal operator ‘operator"" _a1’
     auto blah = "hello world"_a1;

有什么办法可以做到这一点吗?我不能从constexpr返回std::字符串,而且我似乎对模板或decltype无能为力。是否存在从参数中获取常量表达式的方法?

您需要一个模板文字运算符。函数参数从来都不是有效的常量表达式;即使正常使用是有意义的,您的操作员仍然必须支持形式的显式调用

operator "" _a1 ( "hello", 5 );

对于整数和浮动的用户定义文字,有一个模板化表单可以返回array:

template< char ... c >
constexpr std::array< char, sizeof ... (c) >
operator "" _a1 () {
    return { c ... };
}

字符串文字不支持这种方式(目前?),可能是因为多字节编码的问题。

所以,你在这种特殊的方法中运气不佳。

不过,您可以采取另一种策略,将字符串作为数组。

template< std::size_t size >
constexpr std::array< char, size >
string_to_array( char const (&str)[ size ] )
    { return string_to_array( str, make_index_helper< size >() ); }
template< std::size_t size, std::size_t ... index >
constexpr std::array< char, size >
string_to_array( char const (&str)[ size ],
                 index_helper< index ... > )
    { return {{ str[ index ] ... }}; }

这需要支持模板index_helper来生成整数{ 0, 1, 2, ... size }的计数包。

还要注意,constexpr可能不适用于您心目中的应用程序。constexpr函数不能包含命令语句序列。唯一允许计算任何内容的语句是return,或者对于constexpr构造函数,是成员初始化。

更新:这里有一个关于你可以用C++11做什么的小演示。