Fre*_*abe 7 c++ templates visual-studio-2008 visual-studio
在使用Microsoft VisualStudio 2008构建一个小示例程序时,我注意到对传递给模板的类型的推断有些奇怪.考虑这个例子:
template<class T>
void f( T v ) {
x; // trigger a compile error
(void)v;
}
template<class T>
void g( T v ) {
f( v );
}
void h() {
int i;
g<const int &>( i );
}
Run Code Online (Sandbox Code Playgroud)
使用编译此示例会cl /c foo.cpp产生编译错误(按预期).有趣的是'T'模板参数的值.这是VisualStudio 2008打印的内容:
mini.cpp(3) : error C2065: 'x' : undeclared identifier
mini.cpp(9) : see reference to function template instantiation 'void f<int>(T)' being compiled
with
[
T=int
]
mini.cpp(14) : see reference to function template instantiation 'void g<const int&>(T)' being compiled
with
[
T=const int &
]
Run Code Online (Sandbox Code Playgroud)
注意如何进入g,参数的类型const int &只是在f其中int.显然,在推断实例化f模板时要使用的类型时,剥离了引用到const的部分.调整示例以便f调用时
f<T>( v );
Run Code Online (Sandbox Code Playgroud)
类型是const int &在f和g.这是为什么?这是指定的行为吗?我暗中依赖v要传递给的函数参数的类型,f但显然它不是.
答案是尽管变量v具有类型const int &,但表达式 v是带有类型的左值表达式const int.
litb提供文本(5/6):"如果表达式最初具有类型"引用T"(8.3.2,8.5.3),则在进行任何进一步分析之前将类型调整为"T",表达式表示由引用表示的对象或函数,表达式是左值."
"参数"是"由函数调用表达式中的括号限定的逗号分隔列表中的表达式"(1.3.1).所以在14.8.2.1中:
const int.int).int)| 归档时间: |
|
| 查看次数: |
1102 次 |
| 最近记录: |