5

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.

Johannes
  • 2,901
  • 5
  • 30
  • 50
  • 1
    I don't think this is possible, unless I am mistaken. You could use a macro perhaps? `#define LIBRARY_STRUCT(x) library_struct`. Not entirely sure why you want to do this anyhow. – miguel.martin Mar 01 '14 at 08:21
  • possible duplicate of [template argument deduction with strongly-typed enumerations](http://stackoverflow.com/questions/9400581/template-argument-deduction-with-strongly-typed-enumerations) – Jarod42 Mar 01 '14 at 09:58

1 Answers1

1

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • Could you please elaborate on your 3rd approach? Maybe a minimal code example? – Johannes Mar 01 '14 at 09:39
  • @johannes basically it moves the value to no longer being a compile time constant in most useful senses. A function can deduce the type of the enum, but no output type can depend on the value of the enum, which is almost certainly not what you want. Output values can depend, and those values can be `constexpr`. To have a clue if you could use this, details about what your class does with the `enum` value are required. – Yakk - Adam Nevraumont Mar 01 '14 at 14:09
  • https://stackoverflow.com/questions/40960936/infer-enum-class-type-from-enum-class-value-template-parameter This is now possible quite nicely, using C++-17 – CJBrew Mar 10 '20 at 00:39