Friday, January 5, 2018

Fooling around with C++17 (part 1)

New years resolution

In 2018 I will be back writing post here and I will try to be more consistent. I will eventually go back to the subject of 'dynamic like' Java programming but just for fun I will start the year by looking at C++17 (including x14 and x11) C++ is starting too look like a 21 century programming language so I think it is well worth looking at a few features that are starting to make programming really more productive. WARNING: this is not a C++ style guide.

auto this, auto that

C++14 and 17 extend the power of auto and really make it more productive. In C++11 they added the posibility of using auto for the return type of functions but you still had to provide the type using the new arrow syntax. In C++14 they completely removed the need to explicitly provide the type. Here is an example with both syntax:
class LazyCoder
    {
    public:
        auto get_it_Cv11 () -> int
            {
            return 11;
            }

        auto get_it_Cv17 ()
            {
            return 17;
            }
    };
I don't think this is the best use of auto since the type in function declaration is also good documentation (better than comments). In C++11 you could use auto for local variable declaration, for loop variables, function parameters. With C++14 and C++17 you can now also use auto when declaring a variable in the scope of an 'if' and also when doing structured bindings (similar to other languages 'destructuring')
    // Create a tuple
    auto tuple = std::make_tuple(3, 7);

    // C++14
    int i, j;
    std::tie(i,j) = tuple;

    assert (i == 3 && j == 7);

    // C++17 (look ma, no explicit variable declaration)
    auto [x, y] = tuple;

    assert (x == 3 && y == 7);

    // and then ...
    if (auto t = (x != y))
        {
        // I can use t here
        cout << "This is getting ridiculous like t=" << t << endl;
        }
C++z17 has one more trick up its sleeve. The 'structured binding' works with user data types.
    // I have this struct defined somwhere
    struct Zmas
        {
        int z, w;
        };

    // Now I can do this:
    Zmas zmas {7, 11}; // Uniform intialization with curly brackets (next post)
    
    // The number of items between square bracket here must match the number of public 
    // members of Zmas
    auto [z, w] = zmas;

    assert (z == 7 && w == 11);
Of course C++11 addition of auto was already a major improvement when working with complicated types but the latest extensions are even more icing on the cake. For more details about auto check out C++17 Structured Bindings

No comments:

Post a Comment