2013-07-10 36 views
4

我刚刚安装了gcc-4.8.1,当我意识到我可以执行-std = C++ 1y并获得多行constexpr 。我很想知道,有没有做这项工作?从C++中的用户定义文字返回std :: array 11

#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 :: string,并且似乎没有任何我可以用模板或decltype做的事情。无论如何,从参数中获得一个常量表达式?

回答

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,这是一个成员初始化。

更新:Here's的你可以做什么一点点的演示,在C++ 11。

+0

这看起来很酷,我会在它去这个​​afternoon.C++ 14将支持多constexpr功能,但它看起来像我错了,这并没有使它成为GCC呢。 – HNJSlater

+0

这对我很有用,非常感谢! – HNJSlater

相关问题