查看C++接口代码。我没有机会获得执行。我举了一个小例子来说明这种行为。
struct MessageInfo{
MessageInfo() : length{}, from{}, to{} {}
MessageInfo(int _length, string _from, string _to) : length{_length}, from{_from}, to{_to}
{}
int length;
string from;
string to;
using IsEnumerableTag = void;
template<typename F>
void enumerate(F& fun) {
fun(this->length);
fun(this->from);
fun(this->to);
}
};有人能向我解释一下在这个结构定义中枚举结构函数成员的用法吗?
根据我的理解,此结构中的枚举可以将函数类型作为输入参数(函数指针?)
MessageInfo messageInfo (1000, "A", "B");
messageInfo.enumerate<???>(printFrom(messageInfo.From);
void printFrom(string f) {
cout<<"the msgInfo is sent from "<< f<<endl;
}发布于 2022-03-05 19:32:29
它希望您传递一个通用的可调用函数,例如lambda。您不必指定模板参数。它可以从函数参数中推导出来。
例如:
MessageInfo messageInfo (1000, "A", "B");
auto printFields = [](auto&& f){ std::cout << "Value of this field is " << f << ".\n"; };
messageInfo.enumerate(printFields);哪个应该打印
Value of this field is 1000.
Value of this field is A.
Value of this field is B.从这里可以看出,可以使用enumerate对每个成员应用相同的操作,而不必对每个成员重复自己的操作。
签名有点不寻常。通常您会期望F或F&&而不是F&。使用F或F&&,您可以将lambda表达式直接放入调用中,而不必先将其存储在变量中。
https://stackoverflow.com/questions/71365310
复制相似问题