【问题标题】:Passing a function as argument from private function将函数作为私有函数的参数传递
【发布时间】:2020-02-17 04:18:32
【问题描述】:

我有以下代码:

#include <iostream>
#include <vector>
#include <string>
#include <functional>
using namespace std;

struct AStruct {
    string astr;
};

class OtherClass1 {
    public:
        OtherClass1(string s) : str(s) {};
        string str; 
};

class OtherClass2 {
    public:
        OtherClass2(string s) : str(s) {};
        string str; 
};

struct BStruct {
    vector<OtherClass1> vOC1;
    vector<OtherClass2> vOC2;
};


class MainClass {
    public:
        MainClass() {};
        void Update(const BStruct& BS) {
            AStruct v1 = Func(Func1, BS.vOC1);
            AStruct v2 = Func(Func2, BS.vOC2);
            cout << "v1 = " << v1.astr << endl;
            cout << "v2 = " << v2.astr << endl;
        }

    private:
        AStruct Func1(const OtherClass1& oc1) { 
            AStruct AS;
            AS.astr = oc1.str + " oc1 ";
            return AS;
        }
        AStruct Func2(const OtherClass2& oc2) { 
            AStruct AS;
            AS.astr = oc2.str + " oc2 ";
            return AS;
        }
        // AStruct Func3(const OtherClass3& oc3); ...

        template <typename T>
        AStruct Func(function<AStruct(const T&)> Funky, const vector<T>& Foos) {
            AStruct ast;
            for (size_t i = 0; i < Foos.size(); ++i) 
                ast = Funky(Foos[i]);
            return ast;
        }
};

请忽略函数的愚蠢之处,这是我能想到的最简单的方法。想法是 FuncOtherClass1OtherClass2 类的对象执行一些逻辑序列,其中那些对象类由不同的函数处理,通常以向量形式出现。 编译时出错:

error: invalid use of non-static member function ‘AStruct MainClass::Func1(const OtherClass1&)’
   43 |             AStruct v1 = Func(Func1, BS.vOC1);

虽然这可能是一个糟糕的解决方案(设计不佳的结果),但为什么会出现上述错误?

【问题讨论】:

  • 它必须是非静态的吗?从我所见,主类没有任何变量成员。您可以随时将其设为static AStruct Func1(... 并收工。
  • 也许它确实需要是非静态的,因为Func1/2 使用来自MainClass 的成员变量(我没有在这个例子中包括它们,抱歉)。但是这个错误到底是什么?将函数作为参数传递有什么特别之处。

标签: c++


【解决方案1】:

一些函数的类型:

-&amp;MainClass::Func1 : std::function&lt;Astruct(const OtherClass1&amp;)&gt;*

-&amp;MainClass::Func2 : std::function&lt;Astruct(const OtherClass2&amp;)&gt;*

解决此问题的两种方法。

  1. 更改参数类型

  2. 使用 lambda 函数

相关帖子:std::thread calling method of class

【讨论】:

  • 这似乎不是开箱即用的。您是否更改了Func 的定义?它给出了一个参数不匹配错误 (no instance of function template MainClass::Func...)。
  • 我觉得你可以看看stackoverflow.com/questions/10998780/…,C++中的方法和纯函数有点不同
猜你喜欢
  • 2011-11-14
  • 2019-12-28
  • 2021-04-13
  • 2013-01-27
  • 1970-01-01
  • 2023-04-02
  • 2019-11-21
相关资源
最近更新 更多