匿名类可以用作C++中的返回类型吗
Can anonymous class be used as return types in C++?
有没有办法在C++中使用匿名类作为返回类型?
我在谷歌上搜索到这可能有效:
struct Test {} * fun()
{
}
但这段代码没有编译,错误消息是:
在返回类型中不能定义新类型
实际上,代码没有任何意义,我只是想弄清楚匿名类是否可以用作C++中的返回类型。
这是我的代码:
#include <typeinfo>
#include <iterator>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main(int argc, char **argv)
{
int mx = [] () -> struct { int x, y ; } { return { 99, 101 } ; } ().x ;
return 0;
}
我用g++xx.cpp-std=c++0x编译了这段代码,编译器公司:
expected primary-expression before '[' token.
注意:这些代码片段在g++的最新版本中不再工作。我用4.5.2版本编译了它们,但4.6.1和4.7.0版本不再接受它们。
可以在C++11中声明一个匿名结构作为lambda函数的返回类型。但它并不漂亮。此代码将值99分配给mx
:
int mx = [] () -> struct { int x, y ; } { return { 99, 101 } ; } ().x ;
表意输出如下:http://ideone.com/2rbfM
应程的要求:
lambda函数是C++11中的一个新特性。它基本上是一个匿名函数。这里是lambda函数的一个更简单的例子,它不带参数,并返回一个int
:
[] () -> int { return 99 ; }
您可以将其分配给一个变量(您必须使用auto
才能执行此操作(:
auto f = [] () -> int { return 99 ; } ;
现在你可以这样称呼它:
int mx = f() ;
或者你可以直接调用它(这就是我的代码所做的(:
int mx = [] () -> int { return 99 ; } () ;
我的代码只是使用struct { int x, y ; }
来代替int
。末尾的.x
是应用于函数返回值的普通struct
成员语法。
这个功能并不像看上去那么无用。您可以多次调用该函数,以访问不同的成员:
auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } ;
cout << f().x << endl ;
cout << f().y << endl ;
您甚至不必调用该函数两次。这个代码完全符合OP的要求:
auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } () ;
cout << f.x << endl ;
cout << f.y << endl ;
不是他们不能。如错误消息所示,来自ISO/IEC 14882:2011 8.3.5/9:
类型不应在返回类型或参数类型中定义。参数的类型或函数定义的返回类型不应是不完整的类类型(可能是cv限定的(,除非函数定义嵌套在该类的成员规范中(包括在该类中定义的嵌套类中的定义(。
当然,您不能将现有的匿名类型命名为函数声明中的返回类型,因为匿名类没有名称。
尽管您可以为未命名的类创建typedef
并将其用作返回类型,但由于typedef名称成为用于链接目的的类类型的名称,因此该类不再是真正的匿名类。
struct Test {} * a;
decltype(a) fun() {
return a;
}
顺便说一句,struct Test {}
不是一个匿名结构。
在C++14:中,最接近您想要的是
auto f() {
struct {
int x, y;
} ret{10,24};
return ret;
}
int main() {
printf("%i", f().x);
}
该结构未命名(ret是变量名,而不是类型名(,并返回。
如果需要,你仍然可以得到它
using my_struct = decltype(f());
my_struct another; another.x++;
不,您不能在C++中执行类似的匿名类型。
但是,您可以使用typedef
为匿名类型分配新名称。
typedef struct
{
unsigned x;
unsigned y;
} TPoint;
由于@Charles的帖子几乎直接引用了规范来回答这个问题
现在,我想为什么匿名类型不能是函数的返回类型,是因为假设f
返回匿名类型,那么在调用站点会写什么?
????? obj = f();
应该用什么来代替上面代码中的?????
?
- 如何获取std::result_of函数的返回类型
- 奇怪的结构&GCC&clang(void*返回类型)
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 函数作为模板参数,是否对返回类型强制约束
- C++中函数的向量返回类型引发错误
- 检查函数返回类型是否与STL容器类型值相同
- 为什么返回类型中需要typename?C++
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 推导 std::vector::back() 的返回类型
- 在 c++ 中将函数返回类型指定为模板参数
- 使用 SWIG 更改生成的 CS 函数中的返回类型
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 基于返回类型的转换和过载扣除
- 当返回类型声明为 ListNode 时,我们是否可以返回 false<T>*