为什么 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 中,编译器将能够根据返回表达式推断函数返回类型。为什么这不能扩展到任何“表达式 -> 类型”转换?
同样适用于declval,为什么我要写:
std::vector<decltype(declval<X>() + declval<Y>() * declval<Z>())> values;
代替:
std::vector<X+Y*Z> values;
最佳答案
如果隐式添加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;
}
输出:
Value parameter
Type parameter
Type parameter
如果decltype
隐式添加到 t1.foo<x*y+z>();
, 版本错误 foo()
被称为。
- 用于表达您所做的事情的 C++ 策略,并尽可能避免编译器的任何隐式工作是恕我直言,一件非常好的事情。它使内容更易于阅读、理解和维护。
- 毕竟,
decltype
只有8个字母
关于c++ - 为什么 decltype 不是隐含的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24981400/