【问题标题】:How to use functions with different parameters as a function parameter如何使用不同参数的函数作为函数参数
【发布时间】:2016-12-31 04:44:39
【问题描述】:

标题可能有点混乱,所以我会解释得更清楚。

我有这样的课:

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 函数连同该函数参数一起作为输入?

感谢任何帮助!

【问题讨论】:

  • 澄清一下,您希望foo::callFunction 接受给它%Some input% 的参数,并且您希望它调用bar 传递这些参数并返回bar 返回的任何内容? IOW,有点像直通/代理功能?
  • @greatwolf 是的,这就是我想要完成的任务,但我不确定如何去做。

标签: c++ function c++11 parameters parameter-passing


【解决方案1】:

您需要在某个地方知道返回和参数类型。固定在类或模板参数中。

这是一个固定在类中的例子:

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();

请注意,f1f2 仍然是不同类型的实例。模板参数通过推演隐藏。

【讨论】:

  • 这是一个很好的答案!感谢您的帮助,以及 C++17 提示。
猜你喜欢
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
相关资源
最近更新 更多