2017-02-13 15 views
7

Mam ten kod, mam nadzieję, że będą dwie różne wersje operatora () w zależności od typu parametru szablonu.Dlaczego tutaj nie działa opcja 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() 
{ 
} 

Zamiast tego pojawia się błąd kompilacji: '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: Czym jest 'static_cast ();'? – WhiZTiM

+1

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

Odpowiedz

10

Twój operator() nie funkcja szablonów siebie, więc nie ma kontekst SFINAE. Wypróbuj to:

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

Podczas gdy twoja odpowiedź jest poprawna. 'static_cast ();' jest nieprawidłowym wyrażeniem – WhiZTiM

+1

Co to jest 'T' w twojej odpowiedzi? – NeomerArcana

+1

@NeomerArcana To samo, co w 'template struct Impl {...};' – YSC