15

次のコード スニペットを参照してください。std::bindfor overloaded functionを使用したいfoobar。引数なしでメソッドのみを呼び出します。

#include <functional>
#include <iostream>
class Client
{  
  public :  
  void foobar(){std::cout << "no argument" << std::endl;}
  void foobar(int){std::cout << "int argument" << std::endl;}
  void foobar(double){std::cout << "double argument" << std::endl;}
};

int main()
{
    Client cl;  
    //! This works 
    auto a1 = std::bind(static_cast<void(Client::*)(void)>(&Client::foobar),cl);
    a1();
    //! This does not
    auto a2= [&](int)
    {
        std::bind(static_cast<void(Client::*)(int)>(&Client::foobar),cl);
    };
    a2(5);
    return 0;
}
4

1 に答える 1

18

placeholdersバインドされていない引数に使用する必要があります。

auto a2 = std::bind(static_cast<void(Client::*)(int)>(&Client::foobar), cl,
                    std::placeholders::_1);
a2(5);

ラムダ キャプチャを使用してバインドを実行することもできます (これはcl、値ではなく参照によるバインドであることに注意してください)。

auto a2 = [&](int i) { cl.foobar(i); };
于 2012-10-25T08:46:40.917 に答える