如何使is_arithmetic<myClass>::值为真?
How to make is_arithmetic<myClass>::value to be true?
我的想法是,我有一个函数可以对输入进行算术运算,所以可能会像这样:
#include <type_traits>
#include <vector>
using namespace std;
template<typename T>
double mean(const vector<T>& vec)
{
static_assert(is_arithmetic<T>::value, "Arithmetic not possible on this type");
//compute mean (average)
}//mean
这样做效果很好,可以计算出我输入的所有数字类型的平均值
class foo
{
// class that has arithmetic operations created
};// foo
在这个类的定义中,我定义了所需的运算符+和/,这样它们就可以处理预期的输入。现在我想在我的新类中使用mean函数,但由于static_assert,它显然无法编译。那么,如何告诉编译器我的新类应该满足is_arithmetic<foo>::value
呢?
如果当我创建类时,我可以给它一个满足is_argithmic的类型,那就太好了,但这似乎可能会以某种方式导致type_traits的问题?
或者我需要创建一个新的测试,检查
is_arithmetic<T>::value || type(T,foo)
或者类似的东西?
如果可能的话,我宁愿只调整我的类,而不是函数,但我很想找到解决方案。
标准库类型特征,如std::is_arithmetic
,除了一个例外(std::common_type
),都是"固定不变的"。试图专门化它们会导致未定义的行为。is_arithmetic
测试该类型是否是标准定义的算术类型;用户定义的类型从来都不是算术类型。
您可以编写自己的特性来测试对算术运算符的支持:
template<class...> struct voidify { using type = void; };
template<class... Ts> using void_t = typename voidify<Ts...>::type;
template<class T, class = void>
struct supports_arithmetic_operations : std::false_type {};
template<class T>
struct supports_arithmetic_operations<T,
void_t<decltype(std::declval<T>() + std::declval<T>()),
decltype(std::declval<T>() - std::declval<T>()),
decltype(std::declval<T>() * std::declval<T>()),
decltype(std::declval<T>() / std::declval<T>())>>
: std::true_type {};
只有当所有四个表达式都是格式良好的(即T
支持运算符+, -, *, /
)时,部分专门化才会匹配。
演示。
std::is_arithmetic<T>::value
根据定义仅为true
,如果T
是C++标准中的算术类型,则为积分型或浮点型,而这些类型又仅为基本类型:
类型
bool
、char
、char16_t
、char32_t
、wchar_t
以及有符号和无符号整数类型统称为积分类型。有三种浮点类型:
float
、double
和long double
。
相关文章:
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- std::vector的包装器,使数组的结构看起来像结构的数组
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 找到两对数字,使它们的乘积的绝对差最小化
- C++:如何使函数只返回作为列表一部分的字符串
- Python中的for循环与C++有何不同
- c++使用foreach使数组为null
- 使外部项目可用于find_package CMake
- 不确定要在我的main中放入什么才能使我的代码正常工作
- EASTL矢量<向量<int>>连续的
- 是否可以在C++中使变量真正只读
- 有可能使shared_ptr协变吗
- 使lambda不可复制/不可移动
- 学习多线程C++:添加线程不会使执行速度更快,即使它看起来应该
- 如何使用OpenMP使这个循环并行
- 根据变量使Qt UI中的复选框为已选中/未选中
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- C++11编译器何时会使RVO和NRVO优于移动语义和常量引用绑定