6

对于一个库,我想要一个函数来接受另一个函数及其参数,然后将它们全部存储起来以供以后调用。参数必须允许任何类型的混合,但函数只需要返回 void。像这样的东西:

void myFunc1(int arg1, float arg2);
void myFunc2(const char *arg1);
class DelayedCaller
{ ...
public:
    static DelayedCaller *setup(Function func, …);
};

...
DelayedCaller* caller1 = DelayedCaller::setup(&myFunc1, 123, 45.6);
DelayedCaller* caller2 = DelayedCaller::setup(&myFunc2, "A string");

caller1->call(); // Calls myFunc1(), with arguments 123 and 45.6
caller2->call(); // Calls myFunc2(), with argument "A string"

一种方法是让 DelayedCaller::setup() 接受 std::function,并让我的库用户在调用 setup() 之前使用 std::bind()。但是,有没有办法实现 setup() 以便用户不需要自己进行绑定?

编辑:DelayedCaller 是一个现有的类。setup() 是我想添加的一个新的静态方法。

4

4 回答 4

8

一种可能是使用可变参数模板并std::bind()setup()函数内部调用:

#include <iostream>
#include <string>
#include <functional>
#include <memory>

void myFunc1(int arg1, float arg2)
{
    std::cout << arg1 << ", " << arg2 << '\n';
}
void myFunc2(const char *arg1)
{
    std::cout << arg1 << '\n';
}

class DelayedCaller
{
public:
    template <typename TFunction, typename... TArgs>
    static std::unique_ptr<DelayedCaller> setup(TFunction&& a_func,
                                                TArgs&&... a_args)
    {
        return std::unique_ptr<DelayedCaller>(new DelayedCaller(
            std::bind(std::forward<TFunction>(a_func),
                      std::forward<TArgs>(a_args)...)));
    }
    void call() const { func_(); }

private:
    using func_type = std::function<void()>;
    DelayedCaller(func_type&& a_ft) : func_(std::forward<func_type>(a_ft)) {}
    func_type func_;
};

int main()
{
    auto caller1(DelayedCaller::setup(&myFunc1, 123, 45.6));
    auto caller2(DelayedCaller::setup(&myFunc2, "A string"));

    caller1->call();
    caller2->call();

    return 0;
}

输出:

123, 45.6
一个字符串

返回一个智能指针,例如std::unique_ptr,而不是返回一个原始指针(或按值返回并避免动态分配。func_type如果参数是可移动的,则它是可移动的,或者无论如何复制它可能非常便宜。您可能需要定义移动构造函数和移动赋值运算符,它们是在特定条件下生成的)。

于 2013-02-12T13:35:36.790 回答
7

您可以使用 lambda 函数来隐藏绑定:

#include <functional>

class DelayedCaller : public std::function< void(void) > {
public:
    DelayedCaller(std::function< void(void) > fn)
      : std::function< void(void) >(fn) {}
};

DelayedCaller caller1([]() { myFunc1(123, 45.6); });
DelayedCaller caller2([]() { myFunc2("A string"); });

caller1(); // Calls myFunc1(), with arguments 123 and 45.6
caller2(); // Calls myFunc2(), with argument "A string"

这也为您图书馆的用户提供了更大的灵活性。它们不限于单个函数调用,并且函数可以访问它们在其中创建的原始环境:

int x;

DelayedCaller caller3 = [&x]() {
    if (x == 0)
        DoSomething();
    else
        DoSomethingElse();
};
于 2013-02-12T13:08:41.253 回答
0

如果您想/能够使用 C++11未来库,您可以使用std::async

#include <future>

auto caller = std::async(myFunc1, 123, 45.6); // Creates a future object.

caller.get(); // Waits for the function to get executed and returns result.

要强制延迟评估,请使用:

auto caller = std::async(std::launch::deferred, myFunc1, 123, 45.6);

还有一个优点是函数调用可以在使用多核硬件的不同线程上执行。然而,这可能并不适用于所有情况。

于 2013-02-12T13:07:50.553 回答
0

如果您唯一关心的是在保留界面的同时隐藏调用站点的参数绑定,请使用可变参数模板

class DelayedCaller
{
public:
  template<typename... Args>
  static DelayedCaller* setup(void (functionPtr*)(Args...), Args&&... args)
  {
    return new DelayedCaller(std::bind(functionPtr, std::forward<Args>(args)...));
  }

  DelayedCaller(const std::function<void()>& f) : f(f) {}

private:
  std::function<void()> f;
};

公共构造函数仍然为您的用户提供了使用 lambda 对其进行初始化的可能性,如果他们愿意的话。

于 2013-02-12T13:29:05.530 回答