Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass C++11 enum class as template while auto deducing its type

This minimal example compiles without warnings and runs:

// library
template<class T, T t> struct library_struct {};

// user
enum class my_enum { x, y, z };
int main()
{
    library_struct<my_enum, my_enum::x> unused; // l.7
    (void) unused;
    return 0;
}

Now, I want the compiler to deduce the type template parameter my_enum from the enum template paramter my_enum::x. This would look much nicer:

library_struct<my_enum::x> unused;

I have seen examples where the compiler was able to deduce template parameters, but I was only allowed to omit the last template parameters in the template parameter lists. So is it possible to omit the enum type here?

EDIT: I'm interested in solutions without macros.

like image 227
Johannes Avatar asked Mar 01 '14 07:03

Johannes


1 Answers

There are 3 approaches, none of them good.

First, you could wait for a later standard: a number of proposals to fix this problem have been made. I do not know if any made it into C++1y.

Second, macros.

Third, use a deduced type. This forces the enum value to be at best a constexpr parameter.

The shorter answer is 'you cannot do what you ask, at least not cleanly'. The mess has been noted, and may one day be fixed.

like image 156
Yakk - Adam Nevraumont Avatar answered Oct 13 '22 21:10

Yakk - Adam Nevraumont