为什么enable_if不在这里工作?

Neo*_*ana 7 c++ templates

我有这个代码,我的期望是()基于模板参数的类型会有两个不同版本的运算符.

#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()
{
}
Run Code Online (Sandbox Code Playgroud)

相反,我得到一个错误编译: '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)'

w1c*_*h3r 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();
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然你的答案是正确的.`static_cast <U>();`是一个无效的表达式 (5认同)