How to use TypeName in Template (template)
http://blog.csdn.net/caroline_wendy/article/details/23910709
when declaring template parameters, the prefix keyword class and typename can be interchanged;
use keyword typename to identify nested subordinate type names, but not in base class lists and member initialization lists.
subordinate name (dependent names): The name that appears within the template (template), dependent on a template (template) parameter, such as T t;
nested subordinate names (nested dependent names): subordinate names are nested within class, such as T::const_iterator CI;
Non-subordinate name (non-dependent names): does not rely on the name of any template parameter, such as int value;
If you do not specifically point to TypeName, nested subordinate names may result in parsing (parse) ambiguity.
Any time in the template (template) to the middle finger of a nested subordinate type name, you need to add a keyword in the previous position TypeName;
Otherwise the error (GCC): error:need ' TypeName ' before ' t::xxx ' because ' is a dependent scope
Code:
* * * BInsertSort.cpp * * Created on:2014.4.17.
* author:spike * *
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Template<typename t>
void print2nd (const t& container) {typename
t::const_iterator iter ( Container.begin ()); Not add typename, error
++iter;
int value = *iter;
Std::cout << value;
}
int main () {
vector<int> VI = {1,2,3,4,5};
print2nd (vi);
return 0;
}
Output:
2
Exceptions:The nested subordinate type name, if it is
List of base classes (base class list)And
member initial Value column (members initialization list)In
Do not useTypeName
Code:
* * * * BInsertSort.cpp * *
Created on:2014.4.17 * author:spike * *
#include < iostream>
#include <vector>
using namespace std;
struct Number {number
(int x) {
std::cout << "number =" << x << std::endl;
}
};
template<typename t>
struct base{
typedef number Nested;
Template<typename t>
class derived:public base<t>::nested {//No typename public
:
explicit Derived (int x): base<t>::nested (x) {//No typename
TypeName base<t>::nested Temp (7);//must use c27/>}
};
int main () {
derived<int> D (5);
return 0;
}
Output:
Number = 5 number
= 7
When using
Attribute Class (traits Class), you must use TypeName, such as
Code:
* * * * BInsertSort.cpp * *
Created on:2014.4.17 * author:spike * *
#include < array>
#include <iostream>
using namespace std;
Template<typename t>
void Workwithiter (T iter) {
typedef typename STD::ITERATOR_TRAITS<T>:: Value_type Value_type; Use typename
value_type temp (*iter);
Std::cout << "temp =" << temp << std::endl;
}
int main () {
std::array<int, 5> ai = {1,2,3,4,5};
Std::array<int, 5>::iterator aiiter = Ai.begin ();
Workwithiter (aiiter);
return 0;
}
Output:
temp = 1