尾随 return 类型和右值

Trailing return type and rvalues

我正在阅读 Scott Meyers 的 Effective Modern C++,并且正在我的机器上尝试他为 Deducing Types 提供的示例章节.

他提供了这个功能:

template <typename Container, typename Index>
auto decltype_test_1(Container& c, Index i) -> decltype(c[i])
{
  return c[i];
}

然后它以这种方式使用函数:

std::deque<int> d;
…
decltype_test_1(d, 5) = 10; // authenticate user, return d[5],
                          // then assign 10 to it;
                          // this won't compile!

说编译不过。我尝试使用 MSVC,它确实可以编译。我在 main 中写了以下内容:

std::deque<int> d;
d.push_back(0);
d.push_back(1);
d.push_back(2);

decltype_test_1(d, 0) = 10;

for each (auto item in d)
  cout << item << endl;

我不明白为什么它会编译,最重要的是,它显示 10 作为双端队列的第一个元素。对于他所解释的,这段代码是错误的。为什么它在这里工作?我错过了什么?

该评论不是关于带有尾随 decltype 的 C++11 示例,而是关于带有 auto 类型推导的 C++14 版本:

template <typename Container, typename Index>
auto decltype_test_1(Container& c, Index i) //no trailing return
{
  return c[i];
}

使用此版本,示例将无法编译,因为类型将被推导为值而不是引用,因此您不能直接分配给函数调用的结果。

如本书下一页所示,在没有尾随 return 类型的情况下推导出正确类型的方法是使用 decltype(auto) 而不是 auto

template <typename Container, typename Index>
decltype(auto) decltype_test_1(Container& c, Index i)
{
  return c[i];
}