加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么enable_if不在这里工作?

发布时间:2020-12-16 04:56:06 所属栏目:百科 来源:网络整理
导读:我有这个代码,我的期望是基于模板参数的类型会有两个不同版本的operator(). #include string#include type_traitstemplatetypename Tstruct Impl{ std::enable_if_t!std::is_pointerT::value,T operator()(const std::string key,int node) { return static_
我有这个代码,我的期望是基于模板参数的类型会有两个不同版本的operator().
#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,int node)
    {
        return new T();
    }
};

int main()
{
}

相反,我得到一个错误编译:
‘std :: enable_if_t< std :: is_pointer< _Tp> :: value,T> Impl< T> :: operator()(const string&,int)’不能用’std :: enable_if_t<(!std :: is_pointer< _Tp> :: value)重载,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,int node)
{
    return new U();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读