C++ 将方法作为参数传递而无需 lambda

问题描述 投票:0回答:1

我一直在尝试使用模板创建一个包装器,以允许将方法作为参数传递到其他方法中,而不必在基于 这个回复 的 lambda 函数中添加我的调用代码,但遇到了问题。

即,当

computing
Answering
方法不是类
MyClass
的一部分时,解决方案将编译。但是,一旦我使用
MyClass
的一部分的方法,我就会收到以下错误。

智能感知错误:

no sutible constrcuctor exists to convert from "void (std::function<void (int)> callback)" to "std::function<void(std::function<void(int)>)>"

编译器错误:

'MyClass::Computing': non-standard suyntax; use '&' to create pointer to member

我敢打赌我错过了一些非常简单的东西。

我的班级.h

class MyClass{
    MyClass();
    
    void A(std::function<void(int)> func);
    void B(int i);
}

我的班级.cpp

MyClass::MyClass(){
    //Erroring Line
    std::function<void(std::function<void(int)>)> question = TheWrapper(Computing);
    question(Answering);
}

void MyClass::Computing(std::function<void(int)> callback){
    //Thinking deep thoughts

    //Answer
    callback(42);
}
void MyClass::Answering(int i){
    //Shrug
}

包装器.cpp

template<typename F, typename U>
void TheSystem(F Func, U callback) {
    //Submit request in triplicate
    //Burry in a peat bog
    //Dig up
    
    //Start computation of the meaning of life, the universe, and everything
    Func(callback);
}

std::function<void(std::function<void(int)>)> TheWrapper(const std::function<void(std::function<void(int)>)>& Func) {
    return [Func](std::function<void(int)> callback) { TheSystem(Func, callback); };
}
c++
1个回答
0
投票

错误消息是正确的:您使用的语法不标准(尽管旧版本的 MS Visual Studio 支持它);您必须使用

&
来创建指向成员的指针:

... question = TheWrapper(&MyClass::Computing);

这是关于语法的。至于你的目标,有些评论提到了

std::bind
。我从未使用过它,所以不能推荐任何具体的东西,但我确实推荐 lambda。在将它们添加到语言中之前,您必须费尽心思使用指向成员的语法和占位符(如
_1
),阅读可怕的错误消息并抓狂。现在你可以只使用 lambda 了。

© www.soinside.com 2019 - 2024. All rights reserved.