27 May 2008

C++ Typename

On the Schildt's C++ guide, I read time ago about the typename keyword.
Actually, that book cover that topic in few lines, so it wasn't really clear for me, what that keyword did exists for (apart as a substitute for class when using templates).

Until I did this code
template <class K, class V>
class Tree {
...
struct Node {
K key;
V value;
Node *left, *right;
};
Node *search(K k, Node *r);
};


The problem was:
error: expected constructor, destructor, or type conversion before '*' token


template<class K, class V>
Tree<K, V>::Node *Tree<K,V>::search(...) { // << this line
...
}

Imho the best way to teach and learn C/C++ is knowing "why the compiler should work in a certain way".

It seems that Bruce Eckel think in the same way :D
On the second volume of "Thinking in C++" he actually explains why that code doesn't work. And now I've got why the typename does exists.

Simply put, the problem is: template isn't really code until it's instantiated. So the compiler can't know what "Tree::Node" is, because it depends on a template.
So, typename tells the compiler that it's a type and must be treated as such.

After all, Schildt wasn't wrong:
Il secondo uso di typename consente di informare il compilatore che un nome utilizzato nella dichiarazione di un template fa riferimento ad un tipo e non al nome di un oggetto.

The second use of typename informs the compiler that a name used in the declaration of a template refers to a type and not to an object's name.
Stay --sync

0 commenti:

Post a Comment