The same answer as for the rest, but if you want to imitate this behavior, you can (I do not recommend it):
struct Interface { virtual void doStuff() const = 0; virtual ~Interface() {} }; #define newAnon(tmp_name, parents, body, args...) \ ({ \ class tmp_name : \ parents \ { \ body; \ }; \ new tmp_name(##args); \ }) Interface *getDefault() { return newAnon(__tmp__, public Interface, public: virtual void doStuff() const { std::cout << "Some would say i'm the reverse" << std::endl; }); }
Beware, because you cannot have a static member in this new class, and that it uses the Gcc / g ++ operator expression: Statement-Exprs
The solution for the static member will be as follows: imagine that we want the static int to increase in several situations in our previous tmp class, it would look like this:
struct Interface { virtual void doStuff() const = 0; virtual void undoStuff() const = 0; virtual ~Interface() {} }; newAnon(__tmp__, Interface, static int &i() { static int i(0); return i; } public: virtual void doStuff() const { std::cout << "call n°" << i()++ << std::endl; } virtual void undoStuff() const { std::cout << "uncall n°" << i()-- << std::endl; });
As a result, all new pointers specified by getDefault () will refer to the same integer. Note that with C ++ 11 auto, you can access all public members as expected and use the hierarchy to create a child of the specified type:
auto tmp = newAnon(...); struct Try : decltype(*tmp+) { Try() { std::cout << "Lol" << std::endl; } }; Try a;
Update: More modern C ++ (14-17) without extensions will be
#define newAnon(code...) \ [&](auto&&... args) {\ struct __this__ : code;\ return std::make_unique<__this__>(std::forward<decltype(args)>(args)...); \ } auto ptr = new_anon(interface { ... })(arguments);
source share