【发布时间】: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<std::vector<std::string>>(const Entry &)> to_row,然后致电table.set_row(i+1, to_row(valid_entries[i]));。为什么write_data必须知道Table?