我搜索了如何将函数作为参数传递。但是现在我还有一个小问题。
看下面的代码,有一个内部类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
答案 0 :(得分: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) { ... }
}