Jam*_*ard 43 c++ type-inference
据我了解,双方decltype
并auto
会尝试找出的东西是什么类型.
如果我们定义:
int foo () {
return 34;
}
Run Code Online (Sandbox Code Playgroud)
然后这两个声明都是合法的:
auto x = foo();
cout << x << endl;
decltype(foo()) y = 13;
cout << y << endl;
Run Code Online (Sandbox Code Playgroud)
你能否告诉我decltype
和之间的主要区别auto
是什么?
Man*_*rse 43
decltype
给出传递给它的表达式的声明类型.auto
与模板类型推导相同.因此,例如,如果您有一个返回引用的函数,auto
仍然是一个值(您需要auto&
获取引用),但decltype
它将是返回值的类型.
#include <iostream>
int global{};
int& foo()
{
return global;
}
int main()
{
decltype(foo()) a = foo(); //a is an `int&`
auto b = foo(); //b is an `int`
b = 2;
std::cout << "a: " << a << '\n'; //prints "a: 0"
std::cout << "b: " << b << '\n'; //prints "b: 2"
std::cout << "---\n";
decltype(foo()) c = foo(); //c is an `int&`
c = 10;
std::cout << "a: " << a << '\n'; //prints "a: 10"
std::cout << "b: " << b << '\n'; //prints "b: 2"
std::cout << "c: " << c << '\n'; //prints "c: 10"
}
Run Code Online (Sandbox Code Playgroud)
另请参阅DavidRodríguez关于其中只有一个auto
或decltype
可能的地方的答案.
Dav*_*eas 35
auto
(在推断类型的上下文中)仅限于定义具有初始化器的变量的类型.decltype
是一个更广泛的结构,以额外信息为代价,将推断表达式的类型.
在auto
可以使用的情况下,它更简洁decltype
,因为您不需要提供将从中推断出类型的表达式.
auto x = foo(); // more concise than `decltype(foo()) x`
std::vector<decltype(foo())> v{ foo() }; // cannot use `auto`
Run Code Online (Sandbox Code Playgroud)
auto
当为函数使用尾随返回类型时,关键字也用在完全不相关的上下文中:
auto foo() -> int;
Run Code Online (Sandbox Code Playgroud)
这里auto
仅仅是一个领导者,这样编译器知道,这是一个尾随返回类型的声明.虽然上面的例子可以简单地转换为旧样式,但在通用编程中它很有用:
template <typename T, typename U>
auto sum( T t, U u ) -> decltype(t+u)
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,auto
不能用于定义返回类型.
归档时间: |
|
查看次数: |
13802 次 |
最近记录: |