是否可以将重载函数分配给
std::function
对象?
#include <algorithm>
#include <functional>
#include <vector>
int Incr(int x) { return x + 1; }
int Linear(int x) { return 2*x; }
int Square(int x) { return x*x; }
float Square(float x) { return x*x; }
struct BlackBoxInt
{
std::function<int(int)> func;
int operator()(int x) { return func(x); }
};
int main()
{
BlackBoxInt intbox;
std::vector<BlackBoxInt> intboxes;
intbox.func = Incr; // <-- OK
intboxes.push_back(intbox);
intbox.func = Square; // <-- error: no viable overloaded '='
intbox.func = Square(int); // <-- error: expected '(' for function-style cast or type construction
intboxes.push_back(intbox);
intboxes[0].func = Linear; // <-- OK
return 0;
}
您可以将对
Square(int)
的调用包装在 lambda 中并将其分配给 intbox.func
:
intbox.func = [](int x) { return Square(x); };
或者,如果您可以将
Square
制作为函数模板:
template <typename T>
T Square(T x) { return x * x; }
然后您可以将其
int
版本分配给 intbox.func
:
intbox.func = Square<int>;