Lennie De Villiers Lennie De Villiers - 6 months ago 38
C++ Question

Restrict Template Function

I wrote a sample program at http://codepad.org/ko8vVCDF that uses a template function.

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;
cout << "Integer: " << sum(int_values) << endl;

vector<double> double_values;
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.

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.

Another way to implement this is by creating a traits template -- something like this

template<class T>
  const static bool canUseSum = false;

And then specialize it for the classes you want to be ok:

class SumTraits<int>
    const static bool canUseSum = true;

Then in your code, you can write

if (!SumTraits<T>::canUseSum) {
   // throw something here

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