c++ - 使用 enable_if 匹配数字作为函数参数

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

我想使用 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)
{}

关于c++ - 使用 enable_if 匹配数字作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50096540/

相关文章:

c++ - union 中位域的 VStudio C++ 对齐

c++ - SFINAE 用于泛型类型的泛型操作

c++ - 传递失败的模板参数

c++ - 使用 enable_if 专门化结构模板

c++ - QListView的自定义装饰

c++ - friend 类和函数参数的范围

c++ - 修复重载运算符 '+' 的使用不明确?

c++ - 'auto' 和显式变量声明的行为不同

堆栈内存中的c++ lambda

c++ - 将可变模板参数传递给可变函数