Compile-time arguments and function wrappers

Passing values in C++ as a template arguments has some inflexibilities.
For example, if template function has been wrapped into a functor class,
there are no ways to pass some value as a template argument.

There is the following template function:

which requires first template argument to be passed at every call,
but we can’t wrap it to the functor:

As a first attempt, we can move template parameters to the wrapper itself:

Good enough until we want to create this wrapper in one place and pass count in another.


All these can be easily worked around by introducing a new type cval_t
which can hold compile-time value and can be passed as a regular argument.

This is small fragment of cval_t implementation from the CoMeta C++14 metaprogramming library:

In addition to csize_t, which is an alias for cval_t<size_t, value>, there are aliases for int, bool and uint types.

Now we can write the following prototype for the swap function:

and pass all arguments including those that must be known at compile-time to our wrapper:

What about a list of values?

For passing a list of compile-time values to arbitrary functions we can create
a class similar to this:

With this class, passing numeric and boolean constants to various functions is quite easy:

Note, that both ways of passing arguments are perfectly possible:


And we don’t have to write two different prototypes to make both ways work.

Compile-time math

In CoMeta there are operator overloads defined for cval_t and cvals_t types
and all their specializations.
This means that all regular calculations
which can be applied to number constants, can be applied to compile-time values too.

Few examples:

All these techniques are widely used in the KFR C++ DSP framework for template expressions.