为什么decltype不是隐含的?

时间:2014-07-27 13:23:29

标签: 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编译器中,能够根据返回表达式推导出函数返回类型。为什么这不能扩展到任何'表达式 - &gt;输入'转换?

这同样适用于declval,为什么我要写:

std::vector<decltype(declval<X>() + declval<Y>() * declval<Z>())> values;

而不是:

std::vector<X+Y*Z> values;

1 个答案:

答案 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()

  • 用于表达你所做的事情的C ++策略,并且尽可能避免编译器的任何隐式工作是恕我直言,这是一件非常好的事情。它使事情更容易阅读,理解和维护。
  • 毕竟,decltype只有8个字母

Live demo here