【问题标题】:Using enable_if to match numbers as function parameter使用 enable_if 匹配数字作为函数参数
【发布时间】:2018-04-30 08:19:12
【问题描述】:

我想使用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模板参数推导/替换失败

【问题讨论】:

    标签: c++ c++11 enable-if


    【解决方案1】:

    您的T 不可推断(由于::type),一种方法是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      相关资源
      最近更新 更多