Tuesday, November 1, 2016

C++ tips, 2016 Week 43 (24-Oct - 30-Oct-2016)

This is part of my weekly C++ posts based on the daily C++ tips I make at my work. I strongly recommend this practice. If you dont have it in your company start it. List of all weekly posts can be found here.

More explanation can be found in the original post. It should be noted that in general you dont need to be extremely aware of what executes in how many CPU cycles but to have a idea of what is the cost of the different classes of operations or "to have mechanical sympathy".

where template_meta_funct (which is a template class or struct) is the metafunction name, parameter1-4 are the types that are the input parameters and return_value is ... the return value (Note! you can have many return values).

Because the metafunctions depends only on the input parameters and the classes are immutable (the world does not change during evaluation of the return parameters - everything is done at compile time) those functions are pure functions. And that is why template metaprogramming is considered functional programming. Kind of :)

Extremely simple example:

a metafunction that takes a type as input parameter and returns const & to that type:

template<class T>

struct as_constref

{

using type =const T&;

};

usage:

using cref = as_constref<float>::type;

cref takes the return value type which evaluates at compile time to const float&

That's right. The rumors are true! The C++ Standards Committee is in fact removing things from C++! And here they are - the features that are removed from C++ in the incoming standard (C++17). Removed as in "it wont compile if you try to use them"

trigraphs - digraphs and trigraphs are sequences of two and three characters, respectively, that appear in source code and, according to a programming and languages specification, should be treated as if they were single characters. Examples can be found here.