Template-based container iterator

template<class A,class B> void tmp(){ set<int,int>::iterator it; //works set<A,B>::iterator it; // doesn't work } 
+4
source share
1 answer

Due to some rather annoying limitations in C ++ grammar, you should explicitly tell C ++ that set<A,B>::iterator is a type name and not a static member id using the typename keyword. For example, this code compiles just fine:

 #include <set> template<class A, class B> void tmp() { std::set<int,int>::iterator x; // OK typename std::set<A,B>::iterator it; // Also OK } int main() { tmp<int,int>(); return 0; } 

This is because C ++ requires the compiler to make the final decision as to whether set<A,B>::iterator should be interpreted as a type or as a variable / function in grammar analysis; before creating the template. However, before creating a template, it is impossible to make this definition, since in the general case this may depend on the values โ€‹โ€‹of A and B Thus, the compiler will consider it a variable / function, unless explicitly stated otherwise. This results in a parsing error.

+6
source

Source: https://habr.com/ru/post/1338744/


All Articles