繁体   English   中英

C ++使用std :: function从命名空间中返回一个函数

[英]C++ returning a function from within namespace using std::function

我正在尝试使用std::function<type>返回一个函数但是输入有问题...请参阅代码:

#include "LossFunction.hpp"

LossFunction::LossFunction() {
}

LossFunction::LossFunction(int functionType) {
    this->functionType = functionType;
    this->fun = this->getLossFunction();
}

LossFunction::~LossFunction() {
}

std::function<float(Input,Output)> LossFunction::getLossFunction() {
    switch (this->functionType){
        case 0:
            return this->f1;
            break;
        default:
            return this->f1;
            break;
    }
}

我在编译时遇到以下错误:

LossFunction.cpp: In member function ‘std::function<float(Input, Output)>           LossFunction::getLossFunction()’:
LossFunction.cpp:18:17: error: cannot convert ‘LossFunction::f1’ from type     ‘float (LossFunction::)(Input, Output)’ to type ‘std::function<float(Input,  Output)>’
return this->f1;
             ^
LossFunction.cpp:21:17: error: cannot convert ‘LossFunction::f1’ from type ‘float (LossFunction::)(Input, Output)’ to type ‘std::function<float(Input, Output)>’
return this->f1;

问题不在于命名空间,而在于独立和成员功能之间的区别。 独立函数可以传递给std::function的构造函数,但是成员函数需要bind它们的第一个参数,如下所示:

switch (this->functionType){
    case 0:
        return std::bind(&LossFunction::f1, this, _1, _2);
        break;
    default:
        return std::bind(&LossFunction::f1, this, _1, _2);
        break;
}

从错误消息中可以看出f1LossFunction的成员函数。 如果它是一个独立的函数,这将起作用,但是一个成员函数需要一个被调用的对象指针,你可以使用std::bind绑定和存储在std::function ,或者像这样使用lambda:

return [this](Input in, Output out){ return f1(in, out); };

要么

return std::bind(&LossFunction::f1, this);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM