How to pass current class using decltype in c ++ 11?

When I declare a static class method, is it possible to refer to the current class using decltype (or in any other similar style)? For instance,

 class AAA { static AAA const make(); }; 

I am trying to do something like this.

 class AAA { static decltype(*this) const make(); // Not working because there no `this`. }; 

*this used to describe what I want to do. I want to know some decltype() expression that can be solved with AAA .

If possible, how can I do this?

+3
source share
3 answers

In C ++ 1y, you can do this:

 class AAA { public: static auto make() { return AAA(); } }; int main() { AAA aaa = AAA::make(); } 

This is not legal in C ++ 11, since you need to specify the return type for make() . In C ++ 98/03/11 you can:

 class AAA { public: typedef AAA Self; static Self make() { return AAA(); } }; 

It is low-tech, but very readable.

<aside>

You should avoid returning const-qual values โ€‹โ€‹by value. This prevents efficient semantics of movement. If you want to not assign r values, then create an assignment statement qualified with & .

</aside>

+2
source

You could do something like this:

 #include<iostream> class AAA { int _i; public: AAA(int i): _i(i) {} static auto make(int i) -> typename std::remove_reference<decltype(*this)>::type { return {i}; } void print() { std::cout << _i << std::endl; } }; int main() { AAA aaa = AAA::make(1); aaa.print(); return 0; } 

It compiles to GCC 4.7.2 no less :)

<ch / "> EDIT 26 / 11-13: the above code is not legal C ++, although it compiles with gcc, but not with clang or icpc. My apologies.

0
source

Just came up with a way to use member pointers and it seems to work: http://www.tutorialspoint.com/compile_cpp11_online.php?PID=0Bw_CjBb95KQMZHFMdG5SSFBwXzg

 #define self_test(name) \ void dummy__##name(void) {} \ template static T type__##name( void (T::*func)(void) ) { return T(); } \ typedef decltype(type__##name(&dummy__##name)) self__##name; \ static void test( void ) { self__##name::print(); } struct T1 { self_test(X); static void print() { printf( "this is T1\n" ); } }; struct T2 { self_test(X); static void print() { printf( "this is T2\n" ); } }; int main() { T1::test(); T2::test(); } 

This is not ideal either, this requires a compromise with gcc, but at least gcc / VS / Intel will compile it and it works. Also actually gcc / mingw doesn't even require -fpermissive for this.

0
source

Source: https://habr.com/ru/post/1268980/


All Articles