c++ - 为什么 decltype 不是隐含的?

标签 c++ c++11

为什么 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个字母

Live demo here .

关于c++ - 为什么 decltype 不是隐含的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24981400/

相关文章:

c++ - 在 C++98、C++11 交叉编译代码中处理重写的优雅方法?

c++ - 从 std::vector 创建 Eigen::Ref

c++ - 访问 map 中的分区 vector

c++ - Lambda 语法或 gcc 错误的最后一刻更改?

c++ - 绘制贝塞尔曲线的各个部分

c++ - 多重继承 : calling all the overriden functions

c++ - 在 C++ 中使用 MPI 解析大文件

c++ - QT 中有很多错误,缺少组件?

c++ - 为什么 std::numeric_limits<SomeStruct>::infinity() "work"?

c++ - 如何使用 typedef 和可变参数模板包装除一个模板参数之外的所有模板参数?