C++ How to create unique types, from the same template

Consider this template

// this is not a type
template<typename C> buffer {
// every instance of template shares this value
static inline mutable size_t count = 1024U ;

If we create few template definitions we get the same number of distinctive types, like so:

// 3 concrete types
using c_buffer = buffer<char>;

using w_buffer = buffer<wchar>;
using n_buffer = buffer<int> ;

So far so good. But. count is shared. It is the same for everyone. All concrete types defined from the same template and all the instances of those types.

// true
bool the_same_value = c_buffer::count == w_buffer::count == n_buffer::count ;

Since the count is shared on the type level (aka static user-defined type, member) one change applies to every other type.

w_buffer::count  = 13;
bool all_are_13 =  13 == c_buffer::count == w_buffer::count == n_buffer::count ;

This is not so good unless it is a design requirement.

The context

The other day I have developed a handy little template to hold and provide, a plain 2d array on the stack (aka the “matrix”). It is also fully “compile time capable” with the full static internal presentation.  Very handy to enforce (gently) company-wide policies of static matrices in standard C++, and to give in the same time some useful functionality in return. I am calling this template “almost a pod”. Continue reading “C++ How to create unique types, from the same template”

C++ Macros with variable number of arguments

C++ Macros with a variable number of arguments, or even worse sounding “Variadic Macro’s“.

Why would anybody need this? Like C++ is not “hard enough” already, one might exclaim? Well. standard C/C++ is not hard.  But to learn anything properly, good examples are priceless. Here is one good example.

(Working code example)

Continue reading “C++ Macros with variable number of arguments”

C++ How to make unwanted code visible but non-existent

C++ How to make unwanted code visible but non-existent?  Huh, what is “non-existent”?  That is: it is compiled into zero bytes. It is non-existent in the resulting executable.

Ok, but, you might want it back sometime in the near future?  Well, that is simple, say you, there is this well known, mature and universally used macro that does make unused code “get out of the way”

// de-facto standard
#define UNUSED(x) (void)x

If this macro makes you ask questions please read on, otherwise, leave in peace. Continue reading “C++ How to make unwanted code visible but non-existent”

Never underestimate Generic Lambda in Modern C++

Generic Lambda

This is an update of my previous post. With a moral to the story too.  I might hope some C++ beginner might learn something useful here too.

[On-line source code is here]


Having my usual morning workout in the brain gym called cppreference.com, I noticed a comment inside the example snippet on the page  about std::apply

Continue reading “Never underestimate Generic Lambda in Modern C++”