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
:
int mx = [] () -> struct { int x, y ; } { return { 99, 101 } ; } ().x ;
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
:
[] () -> int { return 99 ; }
You can assign this to a variable (you have to use auto
to do this):
auto f = [] () -> int { return 99 ; } ;
Now you can call it like this:
int mx = f() ;
Or you can call it directly (which is what my code does):
int mx = [] () -> int { return 99 ; } () ;
My code just uses struct { int x, y ; }
in place of int
. The .x
at the end is the normal struct
member 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:
auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } ;
cout << f().x << endl ;
cout << f().y << endl ;
You don't even have to call the function twice. This code does exactly what the OP asked for:
auto f = [] () -> struct {int x, y ; } { return { 99, 101 } ; } () ;
cout << f.x << endl ;
cout << f.y << endl ;
The closest you can get to what you want is this, in C++14:
auto f() {
struct {
int x, y;
} ret{10,24};
return ret;
}
int main() {
printf("%i", f().x);
}
The struct is anonymous (ret is a variable name, not a type name), and is returned.
You can still get it if needed with
using my_struct = decltype(f());
my_struct another; another.x++;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With