强制函数只接受一组特定的数据类型 [英] Forcing a function to only accept a certain set of data types
问题描述
有什么方法可以强制函数只接受整数向量(int、unsigned int、uint32_t 等)和那些?我正在尝试编写一个简单的函数,该函数返回具有相同返回类型的所有值的总和(因为我无法确定该值是否大于(2^32 - 1).但是,由于 std::vector
没有用于整个类型的 cout
运算符,我不能做 sum(vector
,因为它将返回一个向量(忽略向量 + 向量不起作用的事实).我不希望重载每种类型来计算某些东西,因为我不需要它.我只是希望函数在 T 是某种形式的 int 时工作(如果可能的话,浮动)
is there any way to force functions to only take in vectors of integers (int, unsigned int, uint32_t, etc.) and only those? im trying to write a simple function that returns the sum of all the values with the same return type (since i cant be sure whether or not the value will be greater than (2^32 - 1). however, since std::vector<T>
doesnt have a cout
operator for the entire type, i cannot do sum(vector<vector<T> >)
, since it will return a vector (ignoring the fact that vector + vector doesnt work). i do not wish to overload every type to cout something because i wont be needing it. i just want the function to work when T is some form of an int (and float if possible)
我尝试过使用 try/except
,但是代码块会捕获类型的运算符,因此如果我执行 sum(vector <vector <T> >),我将无法编译
ive tried using try/except
, but codeblocks catches the operators of the types, so i cant compile if i do a sum(vector <vector <T> >)
template <typename T>
T sum(std::vector <T> in){
try{
T total = 0;
for(int x = 0; x < in.size(); x++)
total += in[x];
return total;
}
catch (int e){
std::cout << "Error " << e << " has occured." << std::endl;
exit(e);
}
}
推荐答案
SFINAE 来救援.
SFINAE to the rescue.
#include <type_traits>
//#include <tr1/type_traits> // for C++03, use std::tr1::
template<bool, class T = void>
struct enable_if{};
template<class T>
struct enable_if<true,T>{
typedef T type;
};
template<class T>
typename enable_if<
std::is_arithmetic<T>::value,
T
>::type sum(std::vector <T> in){
T total = 0;
for(int x = 0; x < in.size(); x++)
total += in[x];
return total;
}
这篇关于强制函数只接受一组特定的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!