【问题标题】:bind a c++ class method (with parameter) to a ref class method将 c++ 类方法(带参数)绑定到 ref 类方法
【发布时间】:2018-05-27 00:59:19
【问题描述】:

我可以将带有参数的 c++ 类方法绑定到 ref 类方法吗?

using Finish = std::function<void(bool status)>;
class Controller
{
public:
    Controller(Finish func);
private:
    Finish m_onFinish;
    bool m_isFinished = false;
}

Controller::Controller(Finish func)
    : m_onFinish(func)
{    
}    
Controller::Execute()
{
    ...
    m_isFinished = true;
    ...
    m_onFinish(m_isFinished)
    ...
}

public ref class MainPage sealed
{
    public :
        MainPage(); 
        void OnFinished(bool status);
    private:
    std::unique_ptr<Controller> m_controller;
}    
MainPage()
{
    auto finishCallBack = std::bind(&OnError, this, std::placeholders::_1);
    m_controller = std::make_unique<Controller>(finishCallBack);
}

我得到以下错误:

error C2664: 'Controller::Controller(const Controller &)': cannot convert argument 1 from 'std::_Binder<std::_Unforced,void (__cdecl *)(bool),MainPage ^,const std::_Ph<1> &>' to 'Finish'

这通常适用于纯 c++。但看起来它不适用于 ref 类。

请提出建议。

【问题讨论】:

  • 也许尝试使用lambda 而不是std::bind
  • 你尝试过论证吗?

标签: c++-cx


【解决方案1】:

基于参数的函数不适用于 std::bind 用于将 c++ 类方法与 ref 类方法绑定。以下解决方法对我有用:

在 C++ 类中

using Finish = std::function<void(bool status)>;

std::vector<Finish> m_funcs;

void Executor()
{
    for(const auto& func : m_funcs)
    {
        // Trigger the function
        func(true);
    }
}

void Register(const std::vector<Finish>& funcs)
{
    m_funcs = funcs
}

主页(UWP 参考类)

m_controller->Register({
            [=] { OnFinish(bool val); /*A method of this class that will be executed from the controller*/ }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-06
    • 2015-06-25
    • 2011-04-07
    • 1970-01-01
    • 2013-04-02
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多