lundi 21 mai 2018

How to use mcu register directly at compile time with this class template

I am experimenting with C++ for Arm Cortex M micro controllers. I wrote a template class to access register with ease without any run time overhead ( inspired from here). It is working correctly, with -Os optimization it does not create any object and provide very efficient code.

#include <cstdint>
template<typename register_address_type,
         typename register_value_type,
         const register_address_type address,
         const register_value_type value = static_cast<register_value_type>(0)>
struct reg final
{
    volatile static register_value_type& reg_get()
    {
        return *reinterpret_cast<register_value_type*>(address);
    }

    static void     reg_set() { reg_get()  = value; }
    static void     reg_and() { reg_get() &= value; }
    static void     reg_or () { reg_get() |= value; }
    static void     reg_not() { reg_get() &= register_value_type(~value); }
};

int main()
{
    reg<uint32_t, uint32_t, 0x8000000, 0x01>::reg_set();
}

But inside reg_set(), reg_and() and other function i m using reg_get() to get reference to register_value_type. Is there any way to make it more readable such that instead of using reg_get() , I can directly write to reg ? e.g.

// I want to write this way with same efficiency.    
static void     reg_set() { reg_value  = value; }

I already have setup for this code at https://godbolt.org/g/74ohQ6

Aucun commentaire:

Enregistrer un commentaire