Is there any way to use anonymous classes in C++ as return types?
I googled that this may work:
struct Test {} * fun()
{
}
But this piece of code doesn’t compile, the error message is:
new types may not be defined in a return type
Actually the code doesn’t make any sense, I just want to figure out whether an anonymous class can be used as return type in C++.
Here is my code:
#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;
}
I compile this code with g++ xx.cpp -std=c++0x, the compiler compains:
expected primary-expression before '[' token.
Notice: These code snippets no longer work in the latest versions of g++. I compiled them with version 4.5.2, but versions 4.6.1 and 4.7.0 no longer accept them.
You can declare an anonymous struct as the return type of a lambda function in C++11. But it’s not pretty. This code assigns the value 99 to
mx:The ideone output is here: http://ideone.com/2rbfM
In response to cheng’s request:
The lambda function is a new feature in C++11. It’s basically an anonymous function. Here is a simpler example of a lambda function, that takes no arguments and returns an
int:You can assign this to a variable (you have to use
autoto do this):Now you can call it like this:
Or you can call it directly (which is what my code does):
My code just uses
struct { int x, y ; }in place ofint. The.xat the end is the normalstructmember syntax applied to the function’s return value.This feature is not as useless as it might appear. You can call the function more than once, to access different members:
You don’t even have to call the function twice. This code does exactly what the OP asked for: