从c++11中用户定义的文字返回std::数组
returning a std::array from a user defined literal in c++11
我刚刚安装了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做什么的小演示。
相关文章:
- 架构决策:返回std::future还是提供回调
- 从 std<Derived>::shared_ptr 的向量返回 std::shared_ptr<Base>
- 在带有尾部斜杠的路径上返回 std::filesystem::create_directories() 的值
- 使用重载 [] 运算符返回 std::map() 的可赋值
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- 为什么 std::gcd/lcm 返回 std::common_type_t<M, N> 而不是 auto?
- 按值返回 std::array
- 返回 std::tuple 中的引用和值
- 返回 std::map with get 方法
- 返回std::string的函数返回零
- 为什么返回std::optional有时移动,有时复制
- std::logic_error 尝试返回 std::string 时
- 如何从 std::async 任务返回 std::tuple
- 返回 std::stringstream - 编译失败
- 当请求的键丢失时,有没有办法从向量映射返回 std::vector ref?
- 成员功能在面向对象的框架中返回std :: vector.size()的效率
- 无法在不移动的情况下从函数返回 std::unique_ptr
- boost-python 当C++方法返回 std::map<string,X*>
- 返回 std::未知大小的数组
- 如何从函数中返回 std::可选<myclass>?