C# "var"和C++ "auto"之间的差异

Differences between C# "var" and C++ "auto"

本文关键字:之间 C++ var auto      更新时间:2023-10-16

我现在正在学习C ,因为我需要编写一些低级程序。

当我了解auto关键字时,它使我想起了C#的var关键字。

那么,C#var和C auto的区别是什么?

c#var关键字仅在函数内部本地工作:

var i = 10; // implicitly typed 

在C 自动关键字中,不仅可以在变量中推导类型,还可以在函数和模板中推导类型:

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;
}

从性能的角度来看,C 中的自动关键字不会影响运行时性能。var关键字也不会影响运行时性能。

IDE的Intellisense支持可能是另一个区别。C#中的VAR关键字可以轻松推导,您将看到带有鼠标的类型。使用C 中的自动关键字,它可能更复杂,这取决于IDE和工具。

要简单地说, autovar要复杂得多。

首先,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

第二,auto可一次使用多个对象:

int f();
int* g();
auto i = f(), *pi = g();

第三,auto用作函数声明中的尾声返回类型语法的一部分:

template <class T, class U>
auto add(T t, U u) -> decltype(t + u);

它也可以用于函数定义中的类型扣除:

template <class T, class U>
auto add(T t, U u) { return t + u; }

第四,将来它可能开始用于声明功能模板:

void f(auto (auto::*mf)(auto));
// Same as:
template<typename T, typename U, typename V> void f(T (U::*mf)(V));

它们是等效的。它们都可以让您自己指定变量的类型,但是变量保持强劲的型。以下行在C#中等效:

var i = 10; // implicitly typed  
int i = 10; //explicitly typed  

,以下行在C 中等效:

auto i = 10;
int i = 10;

但是,您应该记住,在C 中,auto变量的正确类型是使用函数调用的模板参数扣除规则来确定的。