Creating a Guardian Iterator Inside a Function Template

Code compiled using GCC. This work without errors in VC ++

template <typename T>
void Function(T& A){

  T::iterator it; //Error : dependent-name 'T::iterator' is parsed as a non-type,
                  //but instatiation yields a type.
}

This article says that the compiler cannot understand that the iterator in Ttype is a class or just a static member. Therefore, we must use the keyword typenameto classify a character as a type.

My question is what Tis known at compile time, then the compiler already knows what iteratorinside T is a class (in my case, T is vector<int>). So why is the error occurring?

It is also another use of the keyword typenamenext to its use as a template parameter T.

UPDATE:

I read all the answers and other answers here that really answered all my thoughts. I can summarize this: The

correct compiler that handles this right is Gcc. VC ++ will allow you to compile the wrong code. The error that occurs when compiling with Gcc is due to parsing, because Gcc will try to parse the function template code, but it will find a syntax error that is equal T::iterator it;, because Gcc by Deafault treats it T::iteratoras a variable ( T::iteratorparsed as non-type), and not as type, to solve this problem, you must explicitly tell Gcc to handle it T::iteratoras a type, this is done by adding a keyword typename.
Let's get back to VC ++. the answer to why this worked due to an existing error in VC ++, whether VC ++ delays the decision about whether it is a T::iteratorvariable or a type. or VC ++ provides the keyword typename, wherever it is.


Useful article
Note: Feel free to edit UPDATE if you find something wrong.

+5
source share
3 answers

In this article you will find an explanation:

the compiler should be told that the specified character is actually a type and not a static character of this class.

Consider the example from this article :

class ContainsAType {
   class iterator { ... }:
   ...
};

class ContainsAValue {
   static int iterator;
};

, Function() , T::iterator . typename ++.

+2

typename .

, , T , , T ( T ).

, V++ typename.

, ?

, . (. ). , GCC, . , V++ .

DeadMG, V++ , -.

.

+1

T::iterator it;, , T. , T, ( ). , Function . , .

:

template <typename T>
struct A
{
    X x;
};

struct X{};

int main()
{
    A<int> a;
}

X , , . MSVC .

:

template <typename T>
class A : public I_do_not_exist
{
};

, I_do_not_exist (MSVC ).

0

All Articles