【问题标题】:std::bind a static member function inside the classstd::bind 类内部的静态成员函数
【发布时间】:2014-01-28 09:24:59
【问题描述】:

我正在尝试存储一个函数以供以后调用,这是一个 sn-p。

这很好用:

void RandomClass::aFunc( int param1, int param2, double param3, bool isQueued /*= false */ )
{
    /* If some condition happened, store this func for later */
    auto storeFunc = std::bind (&RandomClass::aFunc, this, param1, param2, param3, true);

    CommandList.push( storeFunc );

    /* Do random stuff */
}

但是,如果 RandomClass 是静态的,那么我相信我应该这样做:

void RandomClass::aFunc( int param1, int param2, double param3, bool isQueued /*= false */ )
{
    /* If some condition happened, store this func for later */
    auto storeFunc = std::bind (&RandomClass::aFunc, param1, param2, param3, true);

    CommandList.push( storeFunc );

    /* Do random stuff */
}

但这不起作用,我得到编译错误

错误 C2668: 'std::tr1::bind' : 对重载函数的模糊调用

任何帮助表示赞赏。

【问题讨论】:

  • RandomClass::aFunc 是否存在不止一个重载?
  • 我也可以这样做,这适用于普通类,但不适用于静态版本。 CommandList.push( [=] () { aFunc(param1, param2, param3, true); });
  • 是的,还有第二个 ::aFunc 具有不同的参数。与我尝试使用的函数相比,另一个函数使用字符串并且参数更少。
  • 好的,我找到了一个副本。我希望它会有所帮助。底线是您必须转换为正确的重载类型。

标签: c++ visual-studio-2010 c++11


【解决方案1】:

指向静态成员函数的指针的类型看起来像指向非成员函数的指针:

auto storeFunc = std::bind ( (void(*)(WORD, WORD, double, bool))
                              &CSoundRouteHandlerApp::MakeRoute, 
                              sourcePort, destPort, volume, true );

这是一个简化的例子:

struct Foo
{
  void foo_nonstatic(int, int) {}
  static int foo_static(int, int, int) { return 42;}
};

#include <functional>
int main()
{
  auto f_nonstatic = std::bind((void(Foo::*)(int, int))&Foo::foo_nonstatic, Foo(), 1, 2);
  auto f_static = std::bind((int(*)(int, int, int))&Foo::foo_static, 1, 2, 3);

}

【讨论】:

  • 由于某种原因,我无法投票给您或将其标记为答案。如果有人可以,请将此标记为正确。
  • @StaetonGrey 我认为您可以将其标记为答案,但您需要更多的代表点来投票。
  • 哦,我真傻,我期待一些明显的“接受为答案”按钮,但它只是单击勾号图形:) 是的,直到我得到 15Rep,抱歉!
  • 在std::bind 的调用中显式声明返回和参数类型是否有好处? (或者只是为了帮助解释正在发生的事情)
猜你喜欢
  • 1970-01-01
  • 2021-04-27
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
相关资源
最近更新 更多