【问题标题】:In this case, how do I pass a function as a parameter to the function?在这种情况下,如何将函数作为参数传递给函数?
【发布时间】:2021-09-14 03:58:21
【问题描述】:

我已经搜索了如何将函数作为参数传递。但是现在我还有一个小问题。 看下面的代码,有一个内部类Entry,里面有一个参数代表的模板T。里面的log函数是用来打印调试信息的。里面的Table 类可以画一张桌子。其中set_row(row_number,vector<string> data_vector)是将表的row_number行设置为data_vector中的数据。

template <class T> class SetAssociativeCache {
  public:
    class Entry {
      public:
        uint64_t key;
        uint64_t index;
        uint64_t tag;
        bool valid;
        T data;
    };
  string log(vector<string> headers, function<void(Entry &, Table &, int)> write_data) {
        vector<Entry> valid_entries = this->get_valid_entries(); 
        Table table(headers.size(), valid_entries.size() + 1); // The parameters are the width and height of the table
        table.set_row(0, headers);
        for (unsigned i = 0; i < valid_entries.size(); i += 1)
            write_data(valid_entries[i], table, i + 1);
        return table.to_string();
    }
}

调用日志函数时应该如何传递参数?

模板T类型可能是:

class FilterTableData {
  public:
    uint64_t pc;
    int offset;
};

or

class AccumulationTableData {
  public:
    uint64_t pc;
    int offset;
    vector<bool> pattern;
};

or

class PatternHistoryTableData {
  public:
    vector<bool> pattern;
};

如果我在类外写一个函数给log函数的writedata传参,Entry类型会显示没有这个类型(因为它在类里面)。 如果在内部编写,模板 T 可能是不同的类型。我该怎么办?非常感谢!

在这里我提供一些关于Table 的信息。 他身上有一些功能。

variable:
    unsigned width;
    unsigned height;
    vector<vector<string>> cells;
function:
   Table(int width, int height) : width(width), height(height), cells(height, vector<string>(width)) {}
    void set_cell(int row, int col, string data)
    void set_row(int row, const vector<string> &data, int start_col = 0)
    void set_col(int col, const vector<string> &data, int start_row = 0)
    string to_string()

toString就是把它画出来。

所有代码都在这里。 https://github.com/Yujie-Cui/Bingo/blob/master/prefetcher/bingo_01k.llc_pref

【问题讨论】:

  • 您的描述没有包含足够的信息。您尚未提供有关 Table 是什么的信息 - 这很关键,因为您要询问如何传递接受 Table 作为参数的 std::function (无论它是否包装成员函数)。最后,您显然有using namespace std 生效,这通常是不好的做法(特别是在头文件中,可能会定义模板)并且使其他人更难理解您的代码中的哪些标识符在命名空间std哪些不是。
  • 非常感谢您的回复。我添加了信息。以及所有源代码的URL。
  • 旁白:我认为最好使用std::function&lt;std::vector&lt;std::string&gt;&gt;(const Entry &amp;)&gt; to_row,然后致电table.set_row(i+1, to_row(valid_entries[i]));。为什么write_data 必须知道Table

标签: c++ class templates


【解决方案1】:

你可以写这样的函数

void write_filter_table_data(SetAssociativeCache<FilterTableData>::Entry &, Table&, int) { ... }

或类似的 lambda 表达式

auto write_accumulation_table_data = [](SetAssociativeCache<AccumulationTableData>::Entry &, Table&, int) { ... }

或者你可以写一个模板委托给另一个函数

template <typename T>
auto make_data_writer(std::function<void(T&)> writer) {
    return [writer](SetAssociativeCache<T>::Entry &, Table&, int) { ... }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-17
    • 2020-09-10
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2019-07-13
    相关资源
    最近更新 更多