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

c – 使用enable_if将数字作为函数参数进行匹配

发布时间:2020-12-16 09:20:39 所属栏目:百科 来源:网络整理
导读:我想使用std :: enable_if来构造匹配数字的构造函数.我尝试了以下代码,但找不到构造函数.主要功能有我想要如何使用它的例子.我应该改变什么来使这项工作? #include type_traits#include stringclass A {public: A(const std::wstring,const std::wstring) {
我想使用std :: enable_if来构造匹配数字的构造函数.我尝试了以下代码,但找不到构造函数.主要功能有我想要如何使用它的例子.我应该改变什么来使这项工作?

#include <type_traits>
#include <string>

class A {
public:
    A(const std::wstring&,const std::wstring&)
    {}

    template<typename T>
    A(const std::wstring& n,typename std::enable_if<std::is_arithmetic<T>::value,T>::type v)
    {}
};

int main() {
    A(L"n",1234); // does not compile
    A(L"n",2.7); // does not compile
    A(L"n",L"n"); // compiles
    return 0;
}

错误on Ideone:模板参数扣除/替换失败

解决方法

你的T不可扣除(由于:: type),一种方法是:

template<typename T,typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
A(const std::wstring& n,T v)
{}

(编辑:李大同)

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

    推荐文章
      热点阅读