如何使is_arithmetic<myClass>::值为真?

How to make is_arithmetic<myClass>::value to be true?

本文关键字:何使 gt myClass arithmetic is lt      更新时间:2023-10-16

我的想法是,我有一个函数可以对输入进行算术运算,所以可能会像这样:

#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++标准中的算术类型,则为积分型或浮点型,而这些类型又仅为基本类型:

类型boolcharchar16_tchar32_twchar_t以及有符号和无符号整数类型统称为积分类型

有三种浮点类型:floatdoublelong double