【问题标题】:How can I pass a non-static member function to ftw?如何将非静态成员函数传递给 ftw?
【发布时间】:2020-10-19 11:01:27
【问题描述】:

我是 C++ 编码的新手,我遇到了这个问题: 我想做这样的事情

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <ftw.h>

class Foo {
public: 
    int func1 (const char *fpath, const struct stat *sb, int typeflag){
        total += sb->st_size;
        std::cout << total << std::endl;
        return 0;
    }
    
    int func2(){
        ftw("plots", func1, 3);
    }
    
    int total;
};

是否有解决 func1 不是静态的事实的方法?我还尝试在 func2() 中定义一个 lambda(或 std::function),以便将其传递给 ftw(),但它需要 int (*)(const char*, const stat*, int) 作为第二个参数,因此它不起作用。

提前致谢。

【问题讨论】:

标签: c++ non-static


【解决方案1】:

您可以将std::function 存储在一个静态变量中,并拥有一个“转发”调用的静态函数:

class Foo {
public: 
    int func1 (const char *fpath, const struct stat *sb, int typeflag){
        total += sb->st_size;
        std::cout << total << std::endl;
        return 0;
    }
    
    int func2(){
        ftwForwardTo = [&this] (const char *fpath, const struct stat *sb, int typeflag) {
            return func1(fpath, sb, typeflag);
        };
        ftw("plots", forwardFtw, 3);
    }
    
    int total;

private:
    static std::function<int(const char *, const stat *, int)> ftwForwardTo;

    static int forwardFtw(const char *fpath, const struct stat *sb, int typeflag){
        ftwForwardFunc(fpath, sb, typeflag);
    }
};

我没有测试这段代码,但你明白了。

请注意,这既不是线程安全的也不是可重入的。


在 C++17 中,您可以使用 std::filesystem::recursive_directory_iterator 来获得更简单的解决方案。

对于较旧的 C++ 版本,您可能可以在 Boost 中找到一些东西。

【讨论】:

    【解决方案2】:

    func1有隐藏参数this,表示其签名不符合ftw参数的要求。

    我鼓励你制作静态/全局函数并准备一些全局或单调变量来保存目标函数func1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2014-03-06
      • 1970-01-01
      • 2020-12-31
      • 2015-10-20
      • 2011-01-07
      • 2019-03-14
      相关资源
      最近更新 更多