What is the point of the 'auto' keyword?

后端 未结 8 884
暗喜
暗喜 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 04:13

    HEre's a real life example where I could not, not use auto

    I was trying to do a switch type statement in C++ where the return type is implementation specific and could not be declared easily. So using an 'auto' is probably the right way to resolve the type look up for the map declaration.

    auto foo = boost::bind(&VegaFactory::load_commodity_one_leg,this,conn,_1);
    std::map<std::string,decltype(foo)> methods;
    methods.insert(std::make_pair("FOO",commodityOneLeg));
    
    auto f = methods.find(bar);
    // Call f here
    
    0 讨论(0)
  • 2020-12-16 04:14

    There are a number of uses for auto in C++

    1. Anonymous function objects, aka closures, aka lambda instances. auto is the only way to store them. Types can also be generated derived off those types, and types on their backs, ad infinitum.

    2. C++ can have quite complex types, such as the type of a non mutating iterator into an unordered map that uses a custom allocator and hashing function. typedef can mitigate this, but the type of a m.begin() having a particular name is not that informative: foo_iterator it = is as meaningful as auto foo_iterator =, and the auto one does not require boilerplate elsewhere.

    3. Return type deduction uses the auto keyword, which is required to do some template functions work without huge amounts of traits boilerplate. Eliminating boilerplate is a common theme: C++s robust type system means that types can carry lots of information, and encoding it at every use can be counterproductive.

    4. In some ducktype template code, the work to deduce the type of a variable is roughly the same as the work to code the variables value, and nearly identical in structure, some times literally: decltype(long expression) x = long expression;. auto eliminates that duplication.

    5. Finally in C++1y, type deduction lambdas use auto to say that an argument is a deduced one. Sort of a light weight template. Talk to extend this to non lambdas is also in skunkworks.

    0 讨论(0)
提交回复
热议问题