【问题标题】:can't assign std::bind return value to std::function无法将 std::bind 返回值分配给 std::function
【发布时间】:2017-06-13 04:36:50
【问题描述】:

我一直在尝试编写一段非常简单的代码,但它似乎不起作用,我无法理解编译器错误。

代码:

#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;               
}                   

错误:

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);
                               ^

我正在编译:g++ -std=c++14 bind.cpp。 我看到here 接受的答案建议使用 lambdas 而不是 std::bind 但是,有人能说出为什么上述代码中的第一次和第二次使用都不起作用吗?

【问题讨论】:

    标签: c++ c++11 c++14 bind stdbind


    【解决方案1】:

    您面临的问题与std::stringstream 没有复制构造函数这一事实有关。

    问题可以通过在几个函数中使用const std::stringstream&amp;而不是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;               
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2012-10-29
      相关资源
      最近更新 更多