在 C++/CLI 中是否有与 C#“var”关键字等效的关键字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2007976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:36:46  来源:igfitidea点击:

Is there an equivalent to the C# "var" keyword in C++/CLI?

c#.netc++-clitype-inference

提问by Doc Brown

In C#, I like the varkeyword for situations like this:

在 C# 中,我喜欢在这样的var情况下使用关键字:

var myList = new List<MyType>();

Is there any equivalent in C++/CLI, or do I have to repeat the type name everytime just like this:

C++/CLI 中是否有任何等效项,或者我是否必须每次都重复类型名称,就像这样:

List<MyType ^>^ myList = gcnew List<MyType ^>();

Could not find an explicit statement in the docs or by Google so far. I am using Visual Studio 2008.

到目前为止,在文档或 Google 中找不到明确的声明。我正在使用 Visual Studio 2008。

采纳答案by JaredPar

In Visual Studio 2008 there is no such equivalent. However with Visual Studio 2010 you can use the autokeyword to implement varlike semantics in C++. I know this works with non-managed C++ and I'm fairly certain it works for C++/CLI as well.

在 Visual Studio 2008 中没有这样的等价物。但是,在 Visual Studio 2010 中,您可以使用auto关键字var在 C++ 中实现类似的语义。我知道这适用于非托管 C++,而且我相当确定它也适用于 C++/CLI。

回答by Seva Alekseyev

C++ has typedef. Just alias those hairy types with a typedef, and use the friendly name.

C++ 有 typedef。只需使用 typedef 为那些毛茸茸的类型别名,并使用友好名称。

No, there's no "var" keyword. Vaguely recall there's something to that effect in boost.

不,没有“var”关键字。依稀记得在 boost 中有某种效果。

回答by Max Galkin

I know that type inference is envisioned in the C++1x standard:

我知道C++1x 标准中设想了类型推断:

auto someStrangeCallableType = boost::bind(&SomeFunction, _2, _1, someObject);
auto otherVariable = 5;

Currently, AFAIK, there is no equivalent.

目前,AFAIK,没有等价物。

回答by rmn