/
home
/
Programming
/
Style
/
auto
should only be used for Lambdas, Templates, and Macros.
- // Type is currently unknown
- auto sneed = feed.seed();
- // v Deduced from here:
- QString Feed::seed() { ... }
- // or possibly even here: v
- auto Feed::seed() { return 1; }
- int sneed = 1;
- // ^ type known immediately
- auto sneed = 1;
- // ............^ type known @ EOL
- // char or int?
- auto seed = '1';
- // bool or string?
- auto feed = "false";
- // Perfectly fine and acceptable
- auto sneed = []( int feed ){ return feed += 1024; };
- sneed("seed"); // Will not compile!
- // Dangerous and completely unacceptable
- auto sneed = []( auto feed ){ return feed += 1024; };
- sneed("seed"); // Buffer Overflow
- // Output: "ceFrom == displaceTo"
- // Function Pointer - Works
- int (*sneed)() = [ ]() { return 1; };
- // with capture - WILL NOT COMPILE!
- int (*sneed)() = [&]() { return 1; };
- // Acceptable either way.
- auto sneed = [ ]() { return 1; };
- auto sneed = [&]() { return 1; };
- union Seed;
- union Feed
- {
- int operator+( Feed & ) { return 0 ; };
- QString operator+( Seed & ) { return "feed"; };
- };
- union Seed
- {
- int operator+( Feed & ) { return 1 ; }
- QString operator+( Seed & ) { return "seed"; }
- };
- // This template can now return either an integer, or a string
- template<typename T0, typename T1> auto sneed()
- {
- T0 p;
- T1 q;
- return p + q;
- }
- qDebug() << sneed<Feed,Feed>(); // 0
- qDebug() << sneed<Feed,Seed>(); // "feed"
- qDebug() << sneed<Seed,Feed>(); // 1
- qDebug() << sneed<Seed,Seed>(); // "seed"