#include <iostream>
template <typename T>
struct Node
{
T value;
Node<T>* next;
// will this recurse till the end of the list?
operator Node<const T>()
{
std::cout << "casted" << std::endl;
return Node<const T>{value, (Node<const T>*)next};
}
};
template <typename T>
struct X
{
Node<T>* node;
X(Node<T>* node) : node(node) {}
X<const T> getConst() const
{
return X<const T>((Node<const T>*)node);
}
};
int main()
{
Node<int> node3{ 0, nullptr };
Node<int> node2{ 0, &node3 };
Node<int> node1{ 0, &node2 };
X<int> x(&node1);
auto constX = x.getConst();
std::cout << constX.node->value << std::endl;
}
Output:
0
Here I had a problem where I wanted to cast Node<T>
to Node<const T>
. In the conversion operator, I cast the next
pointer to Node<const T>*
. I thought this might recurse till the end of the list. So I tried to create a list and pass it to X
and call getConst
to see whether the message "casted" will be printed only one time or three times. Surprisingly it didn't print any message. How does conversion operator work? Will it recurse in this example till the end of the list? And why isn't it printing any message?