为什么在期望类型时无法将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
}
在c ++ 14编译器中,能够根据返回表达式推导出函数返回类型。为什么这不能扩展到任何'表达式 - &gt;输入'转换?
这同样适用于declval,为什么我要写:
std::vector<decltype(declval<X>() + declval<Y>() * declval<Z>())> values;
而不是:
std::vector<X+Y*Z> values;
答案 0 :(得分: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;
}
<强>输出:强>
值参数
输入参数
输入参数
如果将decltype
隐式添加到t1.foo<x*y+z>();
,则会调用错误版本的foo()
。
decltype
只有8个字母