c++ - 为什么 enable_if 不能在这里工作?

标签 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()
{
}

相反,我在编译时遇到错误: '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/

相关文章:

c++ - C++中的蓝牙

c++ - 如果存在打开的文件 fd,inotify 不会引发 DELETE_SELF

c++ - 如何查询一个框是否在rtree中

c++ - 由具有不同数量参数的其他函数参数化的函数模板

c++ - 用部分模板特化覆盖抽象成员函数

c++ - std::map 覆盖错误的键

templates - 如何在 go 模板中将 "or"与管道一起使用?

c++遍历模板映射

c++ - 为模板函数专门化模板类

C++:标签/特征模板:确保标签只绑定(bind)一次