【问题标题】:std::bind to non-static member function throwing a bunch of errorsstd::bind 到非静态成员函数抛出一堆错误
【发布时间】:2014-10-29 20:41:35
【问题描述】:

我有一个Button 类,我正在尝试向它添加一个回调函数。在接受this 问题的答案之后,这是我的课程布局:

class Button {
public:
    void SetCallbackFunc(std::function<void()> const& f) {
        callbackFunc = f;
    }
private:
    std::function<void()> callbackFunc;
};

class SomeOtherClass {
public:
    void DoThings();
    void SetupButtonFunctionality() {
        Button *b = new Button();
        b->SetCallbackFunc(std::bind(&SomeOtherClass::DoThings, this, std::placeholders::_1));
    }
};

这些都是我得到的所有编译错误:

error C2977: 'std::add_reference' : too many template arguments
error C2955: 'std::add_reference' : use of class template requires template argument list 
error C2146: syntax error : missing ',' before identifier 'type' (Content\SomeOtherClass.cpp)
error C2065: 'type' : undeclared identifier (Content\SomeOtherClass.cpp)
error C2064: term does not evaluate to a function taking 2 arguments (Content\SomeOtherClass.cpp)
error C2064: term does not evaluate to a function taking 0 arguments (GUI\Button.cpp)
error C2027: use of undefined type 'std::tuple_element<0,_Ftuple>'

代码有什么问题?还有其他简单的方式来写我想要的吗?

【问题讨论】:

    标签: c++ function-pointers std


    【解决方案1】:

    该函数不带参数,所以不需要占位符参数。

    b->SetCallbackFunc(std::bind(&SomeOtherClass::DoThings, this));
    

    【讨论】:

    • 这很有道理,我一直误解那个参数,谢谢。但是,删除后我仍然收到此错误:error C2064: term does not evaluate to a function taking 0 arguments
    • @idlackage 此代码不会生成该错误。您在某处使用调用运算符而不是函数(我相信)。
    • 有关更多信息,请参阅C2064 的文档。
    • 显然发生错误是因为在某些情况下我将callbackFunc 设置为NULL (0) 而不是nullptr。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    相关资源
    最近更新 更多