Take the 2-minute tour ×

I am trying to find template functions that do:

template <typename T>
T add(T lhs, T rhs) {
    return lhs + rhs;

(for add, subtract, multiply, and divide).

I remember there being a standard set of functions for this-- do you remember what they are?

share|improve this question
add comment

2 Answers

up vote 10 down vote accepted

In the header <functional>, you'll find things like std::plus, std::minus, std::multiplies, and std::divides.

They're not functions, either. They're actually functors.

share|improve this answer
They're also not updated properly for C++11.... :( –  Ben Voigt Jun 27 '12 at 21:49
@BenVoigt, I never noticed that :/ –  chris Jun 27 '12 at 21:49
For example, plus's function call operator is T operator()(const T& x, const T& y) const; but should be auto operator()(const T& x, const T& y) const -> declspec(x+y); Don't know how that slipped by the committee. Maybe backward compatibility was deemed more important. –  Ben Voigt Jun 27 '12 at 21:50
@BenVoigt +1 Good to know. Is there a functor that does +=? If not, maybe it's worth it to write my own set of 8 that do what you recommend. –  Oliver Jun 27 '12 at 21:52
@Oliver: I think you'd combine std::accumulate with std::plus, and it might not be quite as efficient. –  Ben Voigt Jun 27 '12 at 21:53
show 4 more comments

You need functors such as std::plus from the <functional> header. See Arithmetic operations here.

These are functors, not functions, so you need an instance to do anything useful:

#include <functional>
#include <iostream>
int main() {

  std::multiplies<int> m;
  std::cout << m(5,3) << "\n";


This seems like overkill in the above sample, but they are pretty useful with standard library algorithms. For example, find the product of elements in a vector:

std::vector<int> v{1,2,3,4,5,6};
int prod = std::accumulate(v.begin(), v.end(), 1, std::multiplies<int>());
share|improve this answer
add comment

Your Answer


