template <class T>
class Node {
private:
T m_value;
//Node* m_ptr; //(1)
//Node<T>* m_ptr; //(2)
};
Can someone explain what is the difference between the above two statements (1) and (2)? Both statements seem to compile, but I can't seem to find what the ISO C++ says about them.
They are the same thing, because you declare the pointer inside the template, thus when you create an instance of Node
the compiler knows what T
is. You don't have to specify the type for a template if it can be deduced, e.g. from argument types, or in this case from the template instance the pointer belongs to.
template <class T>
class Node {
public:
T m_value;
Node* m_ptr; //(1)
//Node<T>* m_ptr; //(2)
};
int main()
{
Node<float> test;
test.m_ptr = new Node<float>{}; // valid
test.m_ptr = new Node<bool>{}; // invalid - triggers compiler error
auto val = test.m_ptr->m_value; // val will be of float type
}