2

我正在阅读 Scott Meyers 的Effective Modern C++,我正在我的机器上尝试他为推导类型一章提供的示例。

他提供了这个功能:

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为双端队列的第一个元素。因为他解释这个代码是错误的。为什么它在这里工作?我错过了什么?

4

1 回答 1

6

该评论不是关于带有尾随 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];
}

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

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

template <typename Container, typename Index>
decltype(auto) decltype_test_1(Container& c, Index i)
{
  return c[i];
}
于 2015-09-07T13:14:04.423 回答