限制模板功能 [英] Restrict Template Function
问题描述
我在 http://codepad.org/ko8vVCDF 上撰写了一个使用模板功能的示例程序。
I wrote a sample program at http://codepad.org/ko8vVCDF that uses a template function.
如何将模板函数限制为只使用数字? (int,double等)
How do I retrict the template function to only use numbers? (int, double etc.)
#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;
}
推荐答案
模板是为了使它使用你想要的类型的东西,其他类型没有。
The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have.
所以,你构造一个int,使用+和+ =,调用一个复制构造函数等。
So, you construct with an int, use + and +=, call a copy constructor, etc.
任何类型的所有这些都将与你的函数一起工作 - 所以,如果我创建一个新类型这些特性,你的函数会工作 - 这是伟大的,不是吗?
Any type that has all of these will work with your function -- so, if I create a new type that has these features, your function will work on it -- which is great, isn't it?
如果你想限制它,更多的功能,只使用定义
If you want to restrict it more, use more functions that only are defined for the type you want.
另一种实现方法是创建一个traits模板 - 类似这样
Another way to implement this is by creating a traits template -- something like this
template<class T>
SumTraits
{
public:
const static bool canUseSum = false;
}
然后专门为你想要的类确定:
And then specialize it for the classes you want to be ok:
template<>
class SumTraits<int>
{
public:
const static bool canUseSum = true;
};
然后在您的代码中,您可以写
Then in your code, you can write
if (!SumTraits<T>::canUseSum) {
// throw something here
}
编辑:如注释中所述,您可以使用BOOST_STATIC_ASSERT使其成为编译时检查,而不是运行时检查
edit: as mentioned in the comments, you can use BOOST_STATIC_ASSERT to make it a compile-time check instead of a run-time one
这篇关于限制模板功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!