I am trying to have a single variable with some type that can be assigned to some of the C standard functors (eg: std::plus
, std::multiplies
, etc...)
Here is the definition for std::plus
(from this link):
template <class T> struct plus : binary_function <T,T,T> {
T operator() (const T& x, const T& y) const {return x y;}
};
I tried
#include <functional>
std::binary_function<int, int, int> func = std::plus;
but it doesn't work. How do I define it properly?
CodePudding user response:
A single variable to hold all kinds of callables with same signature is std::function<int(int,int)>
. Though the functors need to either have the template argument specified or deducde them from arguments:
std::function<int(int,int)> func2 = [](int a,int b){ return std::plus{}(a,b);};
or
std::function<int(int,int)> func = std::plus<int>{};