lundi 27 novembre 2017

Specializing a template method with enable_if

I'm writing a template class that stores a std::function in order to call it later. Here is the simplifed code:

template <typename T>
struct Test
{
    void call(T type)
    {
        function(type);
    }
    std::function<void(T)> function;
};

The problem is that this template does not compile for the void type because

void call(void type)

becomes undefined.

Specializing it for the void type doesn't alleviate the problem because

template <>
void Test<void>::call(void)
{
    function();
}

is still incompatible with the declaration of call(T Type).

So, using the new features of C++ 11, I tried enable_if:

typename std::enable_if_t<std::is_void_v<T>, void> call()
{
    function();
}

typename std::enable_if_t<!std::is_void_v<T>, void> call(T type)
{
    function(type);
}

but it does not compile with Visual Studio:

error C2039: 'type' : is not a member of 'std::enable_if'

How would you tackle this problem?

Aucun commentaire:

Enregistrer un commentaire