c++ - decltype 和 auto 之间的等价性

标签 c++ type-inference auto decltype

因为 auto 和 decltype 都用于推断类型。我想 他们会是一样的。

但是,this 的答案问题表明并非如此。

我仍然认为它们不能完全不同。 我可以想到一个简单的例子,其中 i 的类型在以下两种情况下都是相同的。

auto i = 10; and decltype(10) i = 10;

那么在哪些情况下 auto 和 decltype 的行为可能相同。

最佳答案

auto 的行为完全与模板参数推导相同,这意味着如果您不指定对它的引用,就不会得到一个。 decltype 只是表达式的类型,因此会考虑引用:

#include <type_traits>

int& get_i(){ static int i = 5; return i; }

int main(){
  auto i1 = get_i(); // copy
  decltype(get_i()) i2 = get_i(); // reference
  static_assert(std::is_same<decltype(i1), int>::value, "wut");
  static_assert(std::is_same<decltype(i2), int&>::value, "huh");
}

Live example on Ideone.

关于c++ - decltype 和 auto 之间的等价性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459928/

相关文章:

typescript - 是否可以从 TypeScript 的类型推断中排除 "this"?

c++ - 通用 Lambda

c++ - 如何使用基于范围的for循环迭代器?

c++ - 使用 Visual Studio 2008 在 C++ 中实现逐次逼近算法的问题

c++ - SDL_Event->key.keysym.sym 符号键(冒号、双引号、问号……)

swift - 使用函数时编译时间长(Swift 4)

c++ - 为 auto 键入别名

具有特殊按键布局的 C++ 按键记录器

c++ - std::algorithm 的便利层

c# - Func<S, T> 的 T 仅在 S 和 T 不同时才从 lambda 表达式的输出中推断出来?