6

I've just installed gcc-4.8.1 and was pretty excited when I realised I can do -std=c++1y and get multiline constexpr. I'm curious to know, is there anyway to make this work?

#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;
}

But I get a big horrible:

$ 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;

Is there anyway to make this happen? I can't return a std::string from a constexpr and there doesn't appear to be anything I can do with templates or decltype. Is there anyway to get a constant expression from a parameter?

4

1 回答 1

7

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

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 做的一个小演示。

于 2013-07-10T04:10:59.260 回答