Tom*_*bes 24
在C#中,var关键字只在函数内部工作:
var i = 10; // implicitly typed
Run Code Online (Sandbox Code Playgroud)
在C++中,auto关键字不仅可以在变量中推断类型,还可以在函数和模板中推断类型:
auto i = 10;
auto foo() { //deduced to be int
return 5;
}
template<typename T, typename U>
auto add(T t, U u) {
return t + u;
}
Run Code Online (Sandbox Code Playgroud)
从性能的角度来看,C++中的auto关键字不会影响性能.var关键字也不会影响性能.
另一个区别可能是IDE中的intellisense支持.可以很容易地推断出C#中的Var关键字,你会看到鼠标悬停的类型.使用C++中的auto关键字可能会更复杂,它取决于IDE.
简单地说,auto是一个比它复杂得多的野兽var.
首先,auto可能只是推断类型的一部分; 例如:
std::vector<X> xs;
// Fill xs
for (auto x : xs) x.modify(); // modifies the local copy of object contained in xs
for (auto& x : xs) x.modify(); // modifies the object contained in xs
for (auto const& x : xs) x.modify(); // Error: x is const ref
Run Code Online (Sandbox Code Playgroud)
其次,auto可以用于一次声明多个对象:
int f();
int* g();
auto i = f(), *pi = g();
Run Code Online (Sandbox Code Playgroud)
第三,auto在函数声明中用作尾部返回类型语法的一部分:
template <class T, class U>
auto add(T t, U u) -> decltype(t + u);
Run Code Online (Sandbox Code Playgroud)
它也可以用于函数定义中的类型推导:
template <class T, class U>
auto add(T t, U u) { return t + u; }
Run Code Online (Sandbox Code Playgroud)
第四,将来它可能会开始用于声明函数模板:
void f(auto (auto::*mf)(auto));
// Same as:
template<typename T, typename U, typename V> void f(T (U::*mf)(V));
Run Code Online (Sandbox Code Playgroud)
它们是等价的.它们都允许您不自己指定变量的类型,但变量保持强类型.以下几行在c#中是等效的:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
Run Code Online (Sandbox Code Playgroud)
以下几行在c ++中是等效的:
auto i = 10;
int i = 10;
Run Code Online (Sandbox Code Playgroud)
但是,您应该记住,在c ++中,auto使用函数调用的模板参数推导规则来确定变量的正确类型.
| 归档时间: |
|
| 查看次数: |
11181 次 |
| 最近记录: |