为什么在这里 enable_if 不起作用?

7
我有这段代码,我的期望是根据模板参数的类型,会有两个不同版本的运算符()
#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 :: operator()(const string&,int)'无法与'std :: enable_if_t <(!std :: is_pointer < _Tp> :: value),T> Impl :: operator()(const string&,int)重载。


1
小问题:static_cast<T>();是什么意思? - WhiZTiM
1
@WhiZTiM ftfy - Piotr Skotnicki
1个回答

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<U>(); 是一个无效的表达式。 - WhiZTiM
1
你回答中的T是什么? - NeomerArcana
1
@NeomerArcana 与 template<typename T> struct Impl {...}; 中相同。 - YSC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接