【发布时间】:2014-10-17 22:12:36
【问题描述】:
我的想法是我有一个对输入进行算术运算的函数,所以可能是这样的:
#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
在这个类的定义中,我定义了所需的运算符 + 和 /,因此它们可以处理预期的输入。现在我想在我的新类中使用我的平均函数,但由于 static_assert,它显然不会编译。那么我如何告诉编译器我的新类应该满足 is_arithmetic<foo>::value 呢?
如果我在创建类时可以给它一个满足 is_arithmetic 的类型,那就太好了,但这似乎可能会导致 type_traits 出现问题?
或者我需要创建一个新的测试来检查
is_arithmetic<T>::value || type(T,foo)
还是类似的?
如果可能的话,我宁愿只调整我的类,而不是函数,但我很好奇解决方案。
【问题讨论】:
-
你需要写你自己的特质。
-
@T.C.好吧,我也是这么想的。像
is_like_number这样创建一个新的struct并通过模板规范声明foo是这样简单吗?没关系,你在下面回答。谢谢