匿名类可以在C++中用作返回类型吗?

che*_*eng 11 c++ anonymous-types anonymous-class

有没有办法在C++中使用匿名类作为返回类型?

我用谷歌搜索这可行:

struct Test {} * fun()
{
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有编译,错误信息是:

可能无法在返回类型中定义新类型

实际上代码没有任何意义,我只是想弄清楚一个匿名类是否可以在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;
}
Run Code Online (Sandbox Code Playgroud)

我用g ++ xx.cpp -std = c ++ 0x编译这段代码,编译器得到:

expected primary-expression before '[' token.
Run Code Online (Sandbox Code Playgroud)

Ton*_*nyK 6

注意:这些代码片段不再适用于最新版本的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 ;
Run Code Online (Sandbox Code Playgroud)

ideone输出在这里:http://ideone.com/2rbfM

响应cheng的要求:

lambda函数是C++ 11中的一个新特性.它基本上是一个匿名函数.这是一个简单的lambda函数示例,它不带参数并返回int:

[] () -> int { return 99 ; }
Run Code Online (Sandbox Code Playgroud)

您可以将其分配给变量(您必须使用它auto来执行此操作):

auto f = [] () -> int { return 99 ; } ;
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样调用它:

int mx = f() ;
Run Code Online (Sandbox Code Playgroud)

或者你可以直接调用它(这是我的代码所做的):

int mx = [] () -> int { return 99 ; } () ;
Run Code Online (Sandbox Code Playgroud)

我的代码只是用来struct { int x, y ; }代替int.所述.x在端部是正常struct施加到函数的返回值构件语法.

此功能并非如出现的那样无用.您可以多次调用该函数,以访问不同的成员:

auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } ;
cout << f().x << endl ;
cout << f().y << endl ;
Run Code Online (Sandbox Code Playgroud)

你甚至不必两次调用该函数.此代码完全符合OP的要求:

auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } () ;
cout << f.x << endl ;
cout << f.y << endl ;
Run Code Online (Sandbox Code Playgroud)

  • @TonyK:[它不适用于 `g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1`](https://gist.github.com/1353510) (2认同)

CB *_*ley 5

不是他们不能.如错误消息所示,来自ISO/IEC 14882:2011 8.3.5/9:

不应在返回或参数类型中定义类型.函数定义的参数类型或返回类型不应是不完整的类类型(可能是cv限定的),除非函数定义嵌套在该类的成员规范中(包括在类中定义的嵌套类中的定义) ).

当然,您不能将现有的匿名类型命名为函数声明中的返回类型,因为匿名类没有名称.

虽然您可以typedef为未命名的类创建一个并将其用作返回类型,但是因为typedef名称成为用于链接目的的类类型的名称,所以该类实际上不再是匿名的.