【问题标题】:Can I store bound functions in a container?我可以将绑定函数存储在容器中吗?
【发布时间】:2018-08-24 04:53:50
【问题描述】:

考虑以下代码:

void func_0()
{
    std::cout << "Zero parameter function" << std::endl;
}

void func_1(int i)
{
    std::cout << "One parameter function [" << i << "]" << std::endl;
}

void func_2(int i, std::string s)
{
    std::cout << "One parameter function [" << i << ", " << s << "]" << std::endl;
}

int main()
{
    auto f0 = boost::bind(func_0);
    auto f1 = boost::bind(func_1,10);
    auto f2 = boost::bind(func_2,20,"test");

    f0();
    f1();
    f2();
}

上面的代码按预期工作。有什么方法可以将 f0、f1、f2 存储在容器中并像这样执行它:

Container cont; // stores all the bound functions.
for(auto func : cont)
{
    func();
}

【问题讨论】:

  • 这个问题有帮助吗? stackoverflow.com/questions/15128444/…
  • 不,那是非常不同的。我这里说的是绑定函数。
  • 你使用boost::bind而不是std::bind有什么原因吗?使用auto 表示不再需要使用boost。
  • 我可以使用任一绑定。我使用 auto 只是为了方便。

标签: c++ boost-bind


【解决方案1】:

这个例子对你有用吗?

std::vector<std::function<void()>> container{f0, f1, f2};
for (auto& func : container)
{
    func();
}

你可以read here关于std::function:

std::function 的实例可以存储、复制和调用任何 Callable 目标...

所以这个类模板的模板参数(在我们的例子中是void())仅仅是Callable的签名。 bind() 在您对它的所有调用中返回的正是void() 形式的Callable

【讨论】:

    【解决方案2】:

    std::bind 不保证为具有相同最终接口的函数返回相同的类型(最终 = 绑定后)。因此,不,您将无法将与 std::bind 绑定的函数存储在容器中。您将不得不使用某种类型擦除技术将它们全部归为同一类型,例如std::functionstd::function&lt;void()&gt; 的容器将能够存储您的绑定函数(以类型擦除相关的开销为代价)。

    我不知道它是否适用于boost::bind,但我怀疑在这方面它与std::bind 相同。

    【讨论】:

      猜你喜欢
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多