微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – SFINAE启用非模板成员函数

这可能是一个重复,但我找不到一个OP明显有我遇到的问题.
我有一个类,如果类模板参数不是无符号类型,我试图仅启用运算符.
#include <type_traits>

template<class T>
struct A {
    typename std::enable_if<!std::is_unsigned<T>::value,A>::type operator-() {return {};}
};

int main() {
    A<unsigned> a=a;
}

不幸的是,只要我用无符号类型实例化它就会产生编译错误,如图所示.

main.cpp:5:29: error: no type named 'type' in 'std::enable_if<false,A<unsigned int> >'; 'enable_if' cannot be used to disable this declaration
    typename std::enable_if<!std::is_unsigned<T>::value,A>::type operator-() {return {};}
                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:9:17: note: in instantiation of template class 'A<unsigned int>' requested here
    A<unsigned> a=a;
                ^

好吧,我可以清楚地看到enable_if在这里不起作用.一个模糊的类似问题提到我可以使用继承和模板专门化来解决这个问题,但是……真的没有更好的方法吗?

解决方法

我曾经遇到过同样的问题.事实证明,由于认模板参数不依赖于函数模板中的模板参数,因此无法进行替换失败.您必须将模板参数认为封闭模板类型,如下所示:
template<typename U = T,class = typename std::enable_if<!std::is_unsigned<U>::value,U>::type>
A operator-() { return {}; }

原文地址:https://www.jb51.cc/c/116499.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐