2017-02-13 130 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与模板 struct Impl {...}相同;' – YSC