lundi 20 avril 2015

enable_if with is_enum does not work

MCVE:

#include <type_traits>

template<typename T>
bool func( typename std::enable_if< std::is_enum<T>::value, T >::type &t, int x )
{
}

enum class Bar { a,b,c };

int main()
{
    Bar bar{Bar::a};
    func(bar, 1);
}

I expect func(bar, 1); to match my definition of func however g++ reports:

sfi.cc: In function 'int main()':
sfi.cc:13:17: error: no matching function for call to 'func(Bar&, int)'
      func(bar, 1);
                 ^
sfi.cc:13:17: note: candidate is:
sfi.cc:4:10: note: template<class T> bool func(typename std::enable_if<std::is_e
num<_Tp>::value, T>::type&, int)
     bool func( typename std::enable_if< std::is_enum<T>::value, T >::type &t, int x )
          ^
sfi.cc:4:10: note:   template argument deduction/substitution failed:
sfi.cc:13:17: note:   couldn't deduce template parameter 'T'
      func(bar, 1);
                 ^

Why isn't this working and how do I fix it?

Background: I have an existing function template<typename T> bool func(T &t, int x) and I would like to modify it so there are three different function bodies: one for T being an enum, one for T = unsigned char, and a default for all other types.

I realize it is possible to put enable_if in the return type and make this compile error go away, but then that makes it difficult to implement the other two versions; I'm hoping there's a better solution .

Aucun commentaire:

Enregistrer un commentaire