关于C++中模版常用的的typename和class,先写结论吧:
- 在声明模版参数时,class和typename关键是等价的,可以相互替换。
- 在涉及“嵌套依赖类型名”(nested dependent type name)的时候,必须用typename关键字去标识。
- 规则2有个例外,就是在继承列表或者成员初始化列表中的基类初始化时,可以不用typename去标识“嵌套依赖类型”。
|
1
2
3
4
5
6
|
template
<
typename
T>
void
print2nd(
const
T& container)
{
T::const_iterator * x;
...
}
|
|
1
2
3
|
leoxiang@debian:~$ g++ -std=c++0x
test
.cpp
test
.cpp: In
function
‘void print2nd(const T&)’:
test
.cpp:16: error: ‘x’ was not declared
in
this scope
|
|
1
2
3
4
5
6
|
template
<
typename
T>
void
print2nd(
const
T& container)
{
typename
T::const_iterator * x;
...
}
|
|
1
2
3
4
5
6
7
8
9
10
|
template
<
typename
T>
class
Derived:
public
Base<T>::Nested
//in base class list, no typename
{
public
:
explicit
Derived(
int
x)
: Base<T>::Nested(x)
//in member init list, no typename
{
typename
Base<T>::Nested temp;
//nested dependent type, need typename
}
};
|
7761



被折叠的 条评论
为什么被折叠?



