What is the point of the 'auto' keyword?

后端 未结 8 904
暗喜
暗喜 2020-12-16 03:30

So I understand using var in C# makes sense because you have anonymous types that are compiler derived. C++ doesn\'t seem to have this feature (unless I\'m wron

8条回答
  •  暖寄归人
    2020-12-16 03:57

    C++ does have "anonymous" types - types you cannot refer to by name because the name is not available to you. This was the case even before C++11 and lambdas. Consider the following code:

    class foo {
        class bar { 
          public:
            void baz() { }
        };
      public:        
        static bar func() { return bar(); }
    };
    
    foo::func().baz(); // OK, only the name "bar" is private
    ??? a = foo::func(); // Umm...
    auto b = foo::func(); b.baz(); // Hooray!
    

    Even if not actually declared in a private scope, it is often useful for a library to leave some types unspecified in its API - especially when heavily utilizing expression templates or other template metaprogramming where the type names can be arbitrarily long with all the nested template arguments. Even the standard itself does this - for instance, the result type of std::bind is not defined by the specification.

提交回复
热议问题