使用enable_if匹配数字作为函数参数

Using enable_if to match numbers as function parameter

本文关键字:函数 参数 数字 enable if 使用      更新时间:2023-10-16

我想用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;
}

Ideone 上的错误:模板参数推断/替换失败

你的T是不可推导的(由于::type(,一种方法是:

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