[英]c++ variadic templates fold expression
im reading a book about templates.there's a piece of sample code using a fold expression to traverse a path in a binary tree using operator ->*: 我正在读一本有关模板的书。有一段示例代码使用折叠表达式使用运算符-> *遍历二叉树中的路径:
// define binary tree structure and traverse helpers:
struct Node {
int value;
Node* left;
Node* right;
Node(int i=0) : value(i), left(nullptr), right(nullptr) {
}
//...
};
auto left = &Node::left;
auto right = &Node::right;
// traverse tree, using fold expression:
template<typename T, typename... TP>
Node* traverse (T np, TP... paths) {
return (np ->* ... ->* paths); // np ->* paths1 ->* paths2 ...
}
int main()
{
// init binary tree structure:
Node* root = new Node{0};
root->left = new Node{1};
root->left->right = new Node{2};
//...
// traverse binary tree:
Node* node = traverse(root, left, right);
//...
}
i dont quite understand the line 我不太明白这条线
auto left = &Node::left;
auto right = &Node::right;
as i used to think the :: operator apply to classes will only refer to its static member,maybe i'm wrong in this case,and i do know :: is scope resolution operator, it may refer to Node's left anyway even its not static , but why can it use & operator to get its address? 正如我以前认为::运算符应用于类只会引用其静态成员,也许在这种情况下我错了,而且我确实知道::是作用域解析运算符,无论如何它都可能引用Node的左边static,但是为什么可以使用&运算符获取其地址? actually, what i was considering, is this just an alias like
实际上,我在考虑的是这只是一个别名
using left = &Node::left; // can't compile
only work if 只有在
auto left = &Node::left;
what's the result of auto? 汽车的结果是什么? the explicit type of this expression?
此表达式的显式类型?
note that: the global left and right are used here 注意:这里使用全局的left和right
Node* node = traverse(root, left, right);
which is the last line in main. 这是main中的最后一行。
i 've tried to run it , it all works, but i don't quite get it,how does it work? 我试过运行它,所有方法都可以,但是我不太明白,它如何起作用?
The type of left
and right
is 该类型的
left
和right
是
Node* Node::*left
a case of pointer to class data member . 指向类数据成员的指针的情况。 You can imagine it encodes the offset of
left
within the representation of an unspecified instance of Node
, rather than a fixed position in memory. 您可以想象它会在未指定的
Node
实例表示形式中编码left
偏移,而不是在内存中固定位置。 It can only be dereferenced when this instance is provided, 仅在提供此实例后才能取消引用,
node.*left
(giving a Node*
) or in your case, where the root is a (normal) pointer itself, (给定
Node*
),或者在您的情况下,根本身就是(普通)指针,
root->*left.
This is what the line 这是什么线
return (np ->* ... ->* paths);
unfolds to. 展开到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.