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

Can anonymous class be used as return types in C++?

本文关键字:C++ 返回类型      更新时间:2023-10-16

有没有办法在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();

应该用什么来代替上面代码中的?????