数组作为单行上的右值,与C++2003配合使用
array as rvalue on single line which works with C++2003?
我正在解析一些文本,如果我可以使用数组的右值,而不是在自己的行中定义它,这将使我的生活更轻松。我已经做了这个
int a[]={1,2,3}; //its own line. Do not want
和
func([]()->int*{static int a[]={1,2,3}; return a; }()); //It compiles but untested. It doesn't compile with 2003
我试过
func(int []={1,2,3}); //but got a compile error bc this is simply illegal
我可以把额外的东西放在行的末尾,但不能放在前面。你们有什么想法吗?
func([]()->int*{int a[]={1,2,3}; return a; }()); //works well on C++0x.
我觉得有趣的是,评论效果很好。我不是lambda律师,但我相信上面的代码正在返回一个指向局部变量的指针,这是未定义的行为,所以即使编译了也不意味着它是正确的。
至于引擎盖下发生的事情,我的理解是编译器以类似于(注意,这是一种简化,考虑到没有捕获,确切的lambda:
struct __lambda {
// no captures: no constructor needed, no member objects needed
int* operator()() { // returns int*, no arguments
int a[] = { 1, 2, 3 }; // auto variable
return a; // return &a[0], address of a local object
}
};
我不确定这是否是您想要的,但您可以执行以下操作:
for ( int a[3] = {1, 2, 3}; func( a ), false; );
请注意,Microsoft编译器不支持它,但根据C++’03标准,它是有效的。
在C++03中唯一能做的就是将数组封装在结构/类中。然后可以传递整个对象。
相关文章:
- QAbstractTableModel,并为单行发出dataChanged
- Visual Studio 2019:插入多个C++风格的单行注释
- 将 hh:mm:ss.zzz 时间 QString 转换为毫秒的单行函数?
- 在 Qml 中从 QSqlTableModel 中删除单行时视图不一致
- 单行函数模板 c++ 的内联性保证
- 当输入在带有空格的单行中给出时,cin 如何在 while 循环中工作?
- C++模板是否有助于定义单行'property'成员?
- 如何在单行语句中C++递减多个变量?
- 单行初始化映射中的C++对象
- 叮当格式捕获,单行上有空语句
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- 使用"multiple"命名空间单行
- 单行类声明和实例化
- 格式化宏以使用单行if语句
- C++查找用于构建单行计算器
- 如何在C++中的单行中返回常量数组中的值
- 使用c++libgpiod库,如何将gpio行设置为输出,并使用set_value()函数操作单行
- Visual Studio 2017 是否有用于创建单行注释的特定键盘组合?
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 数组作为单行上的右值,与C++2003配合使用