NeomerArcana
NeomerArcana

Reputation: 2279

Why isn't enable_if working here?

I have this code, my expectation is that there would be two different versions of operator () based on the type of the template parameter.

#include <string>
#include <type_traits>

template<typename T>
struct Impl
{
    std::enable_if_t<!std::is_pointer<T>::value,T> operator()(const std::string& key, int node)
    {
        return static_cast<T>();
    }
    std::enable_if_t<std::is_pointer<T>::value,T> operator()(const std::string& key, int node)
    {
        return new T();
    }
};

int main()
{
}

Instead I get an error compiling: 'std::enable_if_t<std::is_pointer<_Tp>::value, T> Impl<T>::operator()(const string&, int)' cannot be overloaded with 'std::enable_if_t<(! std::is_pointer<_Tp>::value), T> Impl<T>::operator()(const string&, int)'

Upvotes: 7

Views: 424

Answers (1)

w1ck3dg0ph3r
w1ck3dg0ph3r

Reputation: 1011

Your operator() are not function templates themselves, so there is no context for SFINAE. Try this:

template <typename U = T>
std::enable_if_t<!std::is_pointer<U>::value,U> operator()(const std::string& key, int node)
{
    return static_cast<U>();
}

template <typename U = T>
std::enable_if_t<std::is_pointer<U>::value,U> operator()(const std::string& key, int node)
{
    return new U();
}

Upvotes: 10

Related Questions