fold expression does not work when using std::unique_ptr<>

Hi,

The following code will not compile - in particular the traverse() function. I get this error


Error	C2296	'->*': illegal, left operand has type 'std::unique_ptr<Node,std::default_delete<Node>>'
{
^


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
struct Node
{
	int value;
	std::unique_ptr<Node> left;
	std::unique_ptr<Node> right;
	Node(int v = 0) : value{ v }, left{ nullptr }, right{ nullptr } {}
};

template<typename T, typename ...TP>
Node* traverse(T np, TP ...paths)
{
	return (np ->* ... ->* paths);
}

namespace X
{

	auto left = &Node::left;
	auto right = &Node::right;


         void useTraverse()
          {
		std::unique_ptr<Node> root(new Node{ 0 });
		root->left.reset(new Node{ 1 } );
		
		root->left->right.reset(new Node{ 2 });
		root->left->right->right.reset( new Node{ 3 });

		traverse(root.get(), left, right, right);
           }


It worked when I used raw pointers, but now with std::unique_ptr<>'s


Any ideas?


Regards,
Juan
Look at what you need the pack to unfold to:
((root.get()->*left).get()->*right).get()->*right).get();
And compare it with the definition of binary left fold
((((init op E0) op E1) op E2) ...)

This one is better written recursively.

1
2
3
4
5
6
7
8
9
10
11
template <typename T> 
T* traverse(T* last) 
{
    return last; 
}

template <typename T, typename U, typename... Vs>
auto traverse(T* root, U ptr_mem, Vs... ptr_mems)
{
    return traverse((root->*ptr_mem).get(), ptr_mems...); 
}
Last edited on
great solution!!


Thanks!

Juan
Topic archived. No new replies allowed.