thegreatcoder
thegreatcoder

Reputation: 2372

Is there a way to make functions take in an operator as an argument in c++?

Let's suppose I have a function as follows:

#include<iostream>
int func(int a, int b)
{
    return a+b;
}

Without using an if else construct, suppose I want to generalize this function to take in an operator "-" that allows me to return a-b , is there a way for me to do it?

I came across the following link with regard to C and thought it would be a good idea to know if there are any new features in C++ that make this a little easier?

In addition, is there a way for me to store an operator in a variable or pass a reference to it?

Upvotes: 1

Views: 74

Answers (1)

Rietty
Rietty

Reputation: 1156

Yes, you can do this in a limited fashion using templates and callable objects. Simply write the function using a template like so:

#include <iostream>

template <typename T>
int func(int a, int b, T op) {
  return op(a, b);
}

// Call the function here with type.
int main() {
  std::cout << func(5, 8, std::plus<int>());
}

You can pass any of these operator function objects in the manner I have shown.

Upvotes: 4

Related Questions