Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't enable_if working here?

Tags:

c++

templates

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)'

like image 475
NeomerArcana Avatar asked Feb 13 '17 11:02

NeomerArcana


1 Answers

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();
}
like image 66
w1ck3dg0ph3r Avatar answered Sep 24 '22 14:09

w1ck3dg0ph3r