Stunt programming. Modern C++ is not about that.

Stunt programming? Here is one definition. From C2 wiki

Stunt Programming

Doing things the hard or risky way because it is more exciting (and exciting is FUN…until you crash).

I could not agree more with this definition. I have also given practical example using C#, on the same subject sometimes ago.

Modern C++ provides a LOT of opportunity to engage and get one self lost in this kind of programming.

(This is one fairly long post with a lot of C++ code inside.  For newcomers to the modern C++, but not for the beginners. )

As we deliver the code we will discuss the findings.

Requirement: provide storage  for a default value. Deliver the functionality to use it, share it and change it by users.

Note: We will provide the bare minimum.  No resilience in presence of multiple threads, no move semantics and no other modern C++ “stunts”.

Note: to make the code a bit more realistic we shall use few enums from the Gdiplus:: namespace.  GDI+ is a well known artifact to WIN32 aficionados.  To use it one has to place these lines in the header:

Now onto the

Solution design

We shall provide the following interface to the solution:

/* setting up the default to be used elsewhere */
default_width(10);
/* will return the same predefined default value on repeated calls
   will work over compilation units ie, it will be global
*/
auto width = default_width() ;  

To implement this we will use the static value, nested inside a function:

inline int default_width ( int new_ = 1 ) {
      static int dflt_ = new_ ;
          if ( new_ != dflt_ ) dflt_ = new_ ;
    return new_ ;
}

Thus we will achieve lazy instantiation and persistence during the program lifetime. Now the task is simple. Implement the above for any type.

Option One

Hot on the plenty of advice by modern advisers on modern C++ we try and “think” as them and quickly produce the skeleton of the template based function solution.  After all classes (so it seems) are not “en vogue” these days. And we seem to remember seeing some quite exciting mixture of modern C++ features on the subject of templates and functions.

Indeed this looks rather promising. It compiles too. But there are problems. See the comments.

We try and solve them but things suddenly do not go as smooth as they seem to go when advisers present the same kind of solutions.

Especially the usage seems troublesome.  We want some clever snippets here. But alas things do not seem so snazzy all of a sudden.

As an example it seems compiler is “not obeying” when instancing this template : auto the_problem = static_default < REAL, REAL{10} > ; Why is this? Why does it produces “int” instead of function pointer on this line and not on the two instances before?

Hmm, OK. We know better, and we “go back” and take the different path.

Please click on the Page 2 bellow.

Leave a Reply