相关疑难解决方法(0)

是否可以将std :: numeric_limits <T>专门用于用户定义的类似数字的类?

文档std::numeric_limits<T>说它不应该专门针对非基本类型.数字式用户定义类型怎么样?如果我定义了我自己的T表示数值的类型并重载数字运算符,并且表示的信息numeric_limits是有意义的 - 如果我专门numeric_limits针对该类型,会有什么破坏吗?

c++ standards types numbers

24
推荐指数
2
解决办法
4363
查看次数

如何使is_arithmetic <myClass> :: value为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
Run Code Online (Sandbox Code Playgroud)

这很好用,并且计算了我输入的所有数字类型的平均值.但是让我说我​​然后创建一个新类:

class foo
{
    // class that has arithmetic operations created
};// foo
Run Code Online (Sandbox Code Playgroud)

在这个类的定义中,我定义了所需的运算符+和/,因此它们可以使用预期的输入.现在我想在我的新类中使用我的mean函数,但由于static_assert,它显然不会编译.那么如何告诉编译器我的新类应满足is_arithmetic<foo>::value

如果我在创建类时可以给它一个满足is_arithmetic的类型,那会很棒,但这似乎可能会导致type_traits出现问题?

或者我需要创建一个新的测试,检查看看

is_arithmetic<T>::value || type(T,foo)
Run Code Online (Sandbox Code Playgroud)

或类似的东西?

我更愿意只调整我的课程,而不是功能,如果可能的话,但我很想解决问题.

c++ templates

11
推荐指数
1
解决办法
2429
查看次数

标签 统计

c++ ×2

numbers ×1

standards ×1

templates ×1

types ×1