为什么在期望类型时无法将decltype隐式添加到表达式中?
template <class X, class Y, class Z>
auto foo(X x, Y y, Z z){
std::vector<decltype(x+y*z)> values; // valid in c++11/c++14
//std::vector<x+y*z> values; // invalid
values.push_back(x+y*z);
return values; // type deduced from expression - OK
}
Run Code Online (Sandbox Code Playgroud)
在c ++ 14编译器中,能够根据返回表达式推导出函数返回类型.为什么这不能扩展到任何'表达式 - >类型'转换?
同样适用于declval,为什么我要写:
std::vector<decltype(declval<X>() + declval<Y>() * declval<Z>())> values;
Run Code Online (Sandbox Code Playgroud)
代替:
std::vector<X+Y*Z> values;
Run Code Online (Sandbox Code Playgroud)
qua*_*dev 11
如果decltype
允许隐式添加,一些非常常见的模板将变得模棱两可,甚至无法表达.
请考虑以下示例:
struct tp
{
template<typename T>
void foo() { cout << "Type parameter\n"; }
template<int Value>
void foo() { cout << "Value parameter\n"; }
};
int main()
{
const int x = 1;
const int y = 2;
const int z = 3;
tp t1;
t1.foo<x*y+z>();
t1.foo<decltype(x*y+z)>(); // Oops ! different version of foo()
t1.foo<int>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
值参数
输入参数
输入参数
如果decltype
隐式添加t1.foo<x*y+z>();
,foo()
则调用错误的版本.
decltype
只有8个字母现场演示.
归档时间: |
|
查看次数: |
445 次 |
最近记录: |