我有这段代码,我期望会有两个不同版本的运算符 ()
基于模板参数的类型。
#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)'
最佳答案
您的 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();
}
关于c++ - 为什么 enable_if 不能在这里工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42203118/