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
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.Stay --sync
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.
0 commenti:
Post a Comment