TITLE: typename keyword for return values (Newsgroups: comp.std.c++, 19 Oct 98) MICHAUD: "Michel Michaud" Michel Michaud >> >template >> >C::value_type SmallestOf(const C& c) >> > { >> > typename C::const_iterator it= c.begin(); >> > typename C::const_iterator itSmall= it; >> > while (++it != c.end()) >> > if (*it < *itSmall) itSmall= it; >> > return *itSmall; // c must not be empty... >> > } >> > >> >I do understand the need for "typename" in the declaration >> >of it and itSmall, A Standard conforming compiler should >> >interpret C::const_iterator as a non-type without it. CLAMAGE: Steve Clamage >> No, the compiler must reject the code. MICHAUD: >Don't you mean "Yes, and in this case it will reject the code" ? CLAMAGE: Um, I meant to say "Yes, and the compiler in this case must issue a diagnostic message." Compilers are not required to reject code; they are required to complain about invalid code. :-) CLAMAGE: >> Yes. The rule is that a name that depends on a template parameter >> is not a type unless it is declared to be a type with "typename". >> Without the "typename", the compiler must assume C::value_type is >> not the name of a type. (See 14.6 "Name resolution" in the final >> standard. Details have changed since CD2.) MICHAUD: >Is there a specific example of this (as return type)? Because >(see my other post) I don't see the rational of it. It won't >help the compiler in any way, but it will fool most programmers! CLAMAGE: As I explained elsewhere, the compiler doesn't need typename at all. But to enable detection of common sorts of errors in the template code itself, the compiler at a minimum needs to know which names are type names. The compiler can't figure out it's looking at the return type of a function declaration unless it knows the name is indeed the name of a type. Example: A B ( C ) ; If A and C are types, we have a declaration of function B. If A is a type and C is not, we have a definition of object B of type A, initialized with value C. If A is not a type, the code is invalid. It's very hard for a compiler to report an error and continue parsing when it doesn't know what it's looking at. The purpose of adding "typename" was to enable some error detection in template code before instantiation. Hence, the simple rule that a name is not a type name unless it is somehow declared to be a type name.