2

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?

John Dibling
  • 99,718
  • 31
  • 186
  • 324
user
  • 7,123
  • 7
  • 48
  • 90

2 Answers2

10

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.

Community
  • 1
  • 1
chris
  • 60,560
  • 13
  • 143
  • 205
  • @BenVoigt, I never noticed that :/ – chris Jun 27 '12 at 21:49
  • 5
    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. – user 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
  • @BenVoigt, If you're interested, you can post an answer: http://stackoverflow.com/questions/11235299/avoid-duplicated-operator-code-by-using-functors – chris Jun 27 '12 at 21:54
  • @chris: I see his other question there, but I think he's asking the wrong question. – Ben Voigt Jun 27 '12 at 21:55
  • @BenVoigt LOL-- SO is too good! Not only do people answer each others questions, they also *magically know what question they want to ask*! How do you know what question I want to ask? : ) – user Jun 27 '12 at 22:00
  • @Oliver: It seems you want a way to implement your arithmetic operators and compound assignment operators with minimal duplication. That's a reasonable question, answered in the FAQ (I placed a link in a comment on your other question). But you asked how to use functors to reduce duplication. You don't, the solution with functors has more duplication that the method shown in the FAQ. – Ben Voigt Jun 27 '12 at 22:04
6

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>());
juanchopanza
  • 223,364
  • 34
  • 402
  • 480