2

通常の関数で std::bind を実行する方法を読んでいます。そして、フリー関数またはメンバー関数を std::function に格納します。ただし、一方の引数にプレースホルダーを使用し、もう一方の引数に実際の値を使用しようとすると; std::function を呼び出すことができません (コンパイル エラーが発生します)。

そこで、次のコードを試しました。

#include <random>
#include <iostream>
#include <memory>
#include <functional> 

int g(int n1, int n2)
{
    return n1+n2;
}


int main()
{
    using namespace std::placeholders;  // for _1, _2, _3...

    std::function<int(int,int)> f3 = std::bind(&g, std::placeholders::_1, 4);
    std::cout << f3(1) << '\n';

//this works just fine
    auto f4 = std::bind(&g, std::placeholders::_1, 4);
    std::cout << f4(1) << '\n';
}

次のエラー g++ 4.7 が表示されます

prog.cpp: In function 'int main()':
prog.cpp:17:22: error: no match for call to '(std::function<int(int, int)>)         (int)'
     std::cout << f3(1) << '\n';
                  ^
In file included from /usr/include/c++/4.9/memory:79:0,
                 from prog.cpp:3:
/usr/include/c++/4.9/functional:2142:11: note: candidate is:
     class function<_Res(_ArgTypes...)>
       ^
/usr/include/c++/4.9/functional:2434:5: note: _Res         std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res =         int; _ArgTypes = {int, int}]
     function<_Res(_ArgTypes...)>::
     ^
/usr/include/c++/4.9/functional:2434:5: note:   candidate expects 2 arguments, 1 provided
4

2 に答える 2