Skip to content

Cpp11 feature crash cource for Kvasir users

Jay Kickliter edited this page Jun 20, 2017 · 5 revisions

Many users may be new to C++11, especially new syntax enabling new meta programming techniques. Although most of this is only encountered deep in bowls of Kvasir there are a few things the user need to understand to use Kvasir effectively.

The auto keyword

The auto keyword essentially figures out the type of a variable from the type of its initializer:

    auto i = 4;

in this case the compiler can figure out that 4 is an int so i should also be an int. Kvasir relies heavily on the fact the no matter how ugly the type is (in meta programming all 'data' is encoded into the type which can get very verbose) auto will figure it out for you so you don't have to type it.

The constexpr keyword

constexpr is kind of like const except its value can be available at compile time:

    const int i = 4;
    constexpr int j = 4;
    int ai[i]; //error
    int aj[j]; //works

since constexpr values can never change and have whats called 'local linkage' which basically means you cant have an extern constexpr variable the optimizer is very good at removing them if they are unused. The most important thing to remember when looking at a constexpr variable is that it will most likely be optimized away and will not require any ram.

Local initialization of statics

Although many compilers allowed local initialization of constant member variables C++11 officially makes it legal:

    struct S{
        static constexpr int i = 4;
    }; 

this allows users of kvasir to easily refine default settings before passing them to a template:

    struct mySettings : Kvasir::Uart::DefaultSettings{
        static constexpr int baud = 9600;
    };
    struct DebugUart : Kvasir::Uart::Base<DebugUart,mySettings>{
       //your code here
    };