我在 http://codepad.org/ko8vVCDF 写了一个示例程序使用模板函数。
如何将模板函数限制为仅使用数字? (int、double 等)
#include <vector>
#include <iostream>
using namespace std;
template <typename T>
T sum(vector<T>& a)
{
T result = 0;
int size = a.size();
for(int i = 0; i < size; i++)
{
result += a[i];
}
return result;
}
int main()
{
vector<int> int_values;
int_values.push_back(2);
int_values.push_back(3);
cout << "Integer: " << sum(int_values) << endl;
vector<double> double_values;
double_values.push_back(1.5);
double_values.push_back(2.1);
cout << "Double: " << sum(double_values);
return 0;
}
最佳答案
这可以通过使用 SFINAE , 并通过使用来自 Boost 或 C++11 的帮助器变得更容易
提升:
#include <vector>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_arithmetic.hpp>
template<typename T>
typename boost::enable_if<typename boost::is_arithmetic<T>::type, T>::type
sum(const std::vector<T>& vec)
{
typedef typename std::vector<T>::size_type size_type;
T result;
size_type size = vec.size();
for(size_type i = 0; i < size; i++)
{
result += vec[i];
}
return result;
}
C++11:
#include <vector>
#include <type_traits>
template<typename T>
typename std::enable_if<std::is_arithmetic<T>::value, T>::type
sum(const std::vector<T>& vec)
{
T result;
for (auto item : vec)
result += item;
return result;
}
关于c++ - 限制模板功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/148373/