2017-02-13 6 views
7

У меня этот код, я ожидаю, что будут две разные версии оператора (), основанные на типе параметра шаблона.Почему здесь не работает enable_if?

#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() 
{ 
} 

Вместо этого я получаю компиляции ошибки: '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)'

+1

Nit Pick: Что такое 'static_cast ();'? – WhiZTiM

+1

@WhiZTiM [ftfy] (http://coliru.stacked-crooked.com/a/4418f30d119f86fe) –

ответ

10

Ваш operator() не шаблоны функций себя, так что нет никакого контекста для SFINAE. Попробуйте следующее:

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(); 
} 
+5

Хотя ваш ответ правильный. 'static_cast ();' является недопустимым выражением – WhiZTiM

+1

Что такое 'T' в вашем ответе? – NeomerArcana

+1

@NeomerArcana То же, что и в 'template struct Impl {...};' – YSC

Смежные вопросы