Constexpr Fixes

I think this is not possible, but I would like to ask you before giving up on this.

I want something like a constexpr increment.

#include <iostream> constexpr int inc() { static int inc = 0; return inc++; } class Foo { static const int Type = inc(); }; class Foo2 { static const int Type = inc(); }; int main() { std::cout << "Foo1 " << Foo1::Type << st::endl; std::cout << "Foo2 " << Foo2::Type << st::endl; return 0; } 

I do not want to name it in some classes manually (for this I use CRTP) to give each of them its own type, but the type must be const. Anyway, to achieve something similar in C ++? (C ++ 17 + TS)

+7
c ++ metaprogramming constexpr
source share
1 answer

So, there is a Filip Roseen solution called a constant expression counter :

 #include <iostream> template<int N> struct flag { friend constexpr int adl_flag (flag<N>); }; template<int N> struct writer { friend constexpr int adl_flag (flag<N>) { return N; } static constexpr int value = N; }; template<int N, int = adl_flag (flag<N> {})> int constexpr reader (int, flag<N>) { return N; } template<int N> int constexpr reader (float, flag<N>, int R = reader (0, flag<N-1> {})) { return R; } int constexpr reader (float, flag<0>) { return 0; } template<int N = 1> int constexpr next (int R = writer<reader (0, flag<32> {}) + N>::value) { return R; } class Foo { public: static const int Type = next(); }; class Foo2 { public: static const int Type = next(); }; int main() { std::cout << "Foo1 " << Foo::Type << std::endl; std::cout << "Foo2 " << Foo2::Type << std::endl; return 0; } 

Thanks guys :) But this is too risky to use in my main library, which will be used in every project.

PS: I will not close it right now if there is another answer. Because yes it is ugly.

+1
source share

All Articles