标题可能有点乱,我解释的比较清楚。
我有一个类:
class foo
{
public:
foo(%Some function% *) { %Some function pointer% = %Some function%; }
%Some output% callFunction(%Some input%);
private:
%Some function pointer% bar;
}
最好,我希望能够将给定的函数存储在 %Some function pointer%
中,以便在整个类中使用,但这不是必需的。
所以我的主要问题是:
我如何才能创建一个真正的 callFunction
,它可以将 any 函数作为输入,以及该函数的参数?
感谢任何帮助!
最佳答案
您需要在某处知道返回类型和参数类型。在类或模板参数中固定。
这是类中固定的示例:
struct foo {
foo(std::function<int(std::string, double)> func) : bar{std::move(func)} {}
int callFunction(std::string s, double d) {
bar(std::move(s), d);
}
private:
std::function<int(std::string, double)> bar;
};
此方法不仅允许函数指针,还允许任何类似函数的对象,例如 lambda。
如果你不想固定类型,那么你可以使用模板来指定你想要包装的函数对象的类型:
template<typename F>
struct foo {
foo(F func) : bar{std::move(func)} {}
template<typename... Args>
auto callFunction(Args&&... args) -> decltype(bar(std::declval<Args>()...)) {
return bar(std::forward<Args>(args)...);
}
private:
F bar;
};
template<typename F>
auto make_foo(F f) {
return foo<F>{std::move(f)};
}
此方法允许任何函数或类函数对象,而且比其他解决方案更快,因为它不会拖累 std::function
开销。这里的缺点是您必须在 C++17 之前使用 make_foo
。
然后您可以像这样使用上面的解决方案:
auto f1 = make_foo([](int i){ return i * 1.5; });
auto f2 = make_foo([]{});
double result = f1.callFunction(12);
f2.callFunction();
如果你打开 C++17 的开关,那么你可以这样写:
foo f1 = [](int i){ return i * 1.5; };
foo f2 = []{};
double result = f1.callFunction(12);
f2.callFunction();
注意 f1
和 f2
仍然是不同类型的实例。通过推导隐藏模板参数。
关于c++ - 如何使用具有不同参数的函数作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41405544/