2017-06-13 4 views
2

非常に単純なコードを書くことを試みてきましたが、動作していないと思われ、コンパイラから意味をなさないエラー。std :: bind戻り値をstd :: functionに代入することができません

コード:

#include <iostream> 
#include <sstream> 
#include <functional> 

class c 
{ 
public: 
    void test(std::stringstream ss){ 
     std::cout<<ss.str()<<std::endl; 
    } 

    void test2(std::stringstream ss){ 
     const auto bound=std::bind(&c::test,this, ss); 
     std::function<void()> f(bound); 
     f(); 
    } 

}; 

void test1(const std::stringstream ss){ 
    std::cout<<ss.str()<<std::endl; 
} 

int main(){   
    std::stringstream ss; 
    ss<<"hello world"; 

    //first 
    const auto bound=std::bind(&test1,ss); 
    std::function<void()> f(bound); 
    f(); 
    //second 
    C obj; 
    obj.test2(ss); 
    return 0;    
}     

エラー:g++ -std=c++14 bind.cpp:私は

bind.cpp:14:32: error: no matching function for call to ‘std::function<void()>::function(const std::_Bind<std::_Mem_fn<void (c::*)(std::__cxx11::basic_stringstream<char>)>(c*, std::__cxx11::basic_stringstream<char>)>&)’ 
    std::function<void()> f(bound); 
          ^
bind.cpp:30:31: error: no matching function for call to ‘std::function<void()>::function(const std::_Bind<void (*(std::__cxx11::basic_stringstream<char>))(std::__cxx11::basic_stringstream<char>)>&)’ 
    std::function<void()> f(bound); 
          ^

をコンパイルしています。 私はhereを参照してください。受け入れられた答えでは、std :: bindの代わりにlambdasを使用することを提案しましたが、上記のコードの第1および第2の使い方がうまくいかない理由を誰でも知ることができますか?

答えて

4

あなたが直面している問題は、std::stringstreamにコピーコンストラクタがないという事実と関係があります。

2つの関数でstd::stringstreamの代わりにconst std::stringstream&を引数の型として使用すると、問題を解決できます。

#include <iostream> 
#include <sstream> 
#include <functional> 

class c 
{ 
    public: 

    // Change the argument to a const& 
    void test(std::stringstream const& ss){ 
     std::cout<<ss.str()<<std::endl; 
    } 

    // Use std::cref to use a const& in the call to std::bind 
    void test2(std::stringstream ss){ 
     const auto bound=std::bind(&c::test,this, std::cref(ss)); 
     std::function<void()> f(bound); 
     f(); 
    } 

}; 

// Change the argument to a const& 
void test1(const std::stringstream & ss){ 
    std::cout<<ss.str()<<std::endl; 
} 

int main(){   
    std::stringstream ss; 
    ss<<"hello world"; 

    //first 
    // Use std::cref to use a const& in the call to std::bind 
    const auto bound = std::bind(&test1, std::cref(ss)); 
    std::function<void()> f = bound; 
    f(); 
    return 0;    
} 
関連する問題