Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
239 lines (204 sloc) 4.28 KB

The art of manufacturing types

canvas

…​

canvas

…​

canvas
constexpr auto pra = ciaa[Register::PRA];
const auto value   = read_l<pra>();

Auto

canvas

auto

…​

canvas

c++03

typedef
    PyMessageFactory::ClassesByMessageMap::iterator iterator;

for (iterator it = self->classes_by_descriptor->begin();
    it != self->classes_by_descriptor->end(); ++it) {
    ...
}

…​

canvas

c++11

for(auto& item : *(self->classes_by_descriptor))
    ...
}

…​

canvas

auto all the things?

…​

canvas

was it signed, unsigned, 8/16/32/64 bits, happy? sad?

auto square(auto arg)
{ return arg*arg; }

¯\_(ツ)_/¯

…​

canvas

no lambdas without auto

const auto lambda = [](int arg)
{ return arg*arg; };

…​

canvas

i knew all of this, where are you going?

Factories

canvas

manufacture all the things!

…​

canvas

a lock factory

constexpr auto make_lock(int key, int value)
{ // -> (fn(int) -> std::optional<int>)

    return [key,value](auto _key) -> std::optional<int>
    {
        return key == _key ?
            std::make_optional(value) :
            std::nullopt;
    };
};

…​

canvas
constexpr auto key     = 42;
constexpr auto value   = 1337;
constexpr auto my_lock = make_lock(key, value);

…​

canvas
static_assert( std::nullopt == my_lock(84) );
static_assert( 1337         == my_lock(42) );

…​

canvas

what if we have one key, and want to try which lock it fits?

…​

canvas
constexpr auto make_branch(auto left, auto right)
{ // -> (fn(int) -> std::optional<int>)

    return [left,right](int key) -> std::optional<int>
    {
        const auto result = left(key)
        if( result != std::nullopt )
        {
            return result;
        }
        return right(key);
    };
};

…​

canvas

with some makeup

constexpr auto lkup = make_lookup(
    map('A',13),
    map('B',55),
    map('C',87)
);

const int my_native_array[ lkup['B'] ];

…​

canvas
constexpr auto ciaa = make_lookup(
    map(Register::PRA, reg{0xBFE001, Width::B, Access::R}),
    map(Register::PRB, reg{0xBFE101, Width::B, Access::R}),
    ...
);
template<uint32_t reg_serialized>
inline uint32_t read_l()
{
    constexpr auto r = reg{reg_serialized};
    static_assert(r.access() == Access::R);
    static_assert(r.width() == Width::L);
    return *reinterpret_cast<volatile const uint32_t*>
        (r.address());
}

…​

canvas
constexpr auto pra = ciaa[Register::PRA];
const auto value   = read_l<pra>();
#define PRA 0xBFE001
#define READ_LONG_REG(x) *((long *) (x))
const auto value = READ_LONG_REG(PRA);

<iframe width="800px" height="200px" src⇒</iframe> </body>

Compiler explorer