Introducing concepts in ledboard project

In near feature we’ll able to write nifty constrains for template arguments using concepts (C++20). I’m currently researching common use cases and trying to adopt them in my ledboard project. With GCC >= 8.1 you can enable concepts using `-fconcepts` instrumentation compile flag, but this feature is not standardized yet. The current implementation and specification on concepts might change, keep this in mind. With recent talk at CppCon by Bjarne Stroustrup we get a pretty bold picture that this feature is essential and simplify things (see Bjarne Stroustrup “Concepts: The Future of Generic Programming (the future is here)”). From my perspective them main advantage is to write zero-cost abstraction with better constrains and maintainability and get rid of template error novel.

Below there is code that I’m currently using for as static interface for my animation classes, take a look:

template<typename type>
concept bool animation_interface = requires(type a) {
    { a.value() } -> rgb // animation_interface must have method value() that returns rgb type
    { a.r() } -> u8 // requires a.r() method with integer return type 
    { a.g() } -> u8 // ...
    { a.b() } -> u8 // ...
    { a.step() } -> void // requires callable a.step() method without return type
};

// without constrains
template <typename type>
constexpr auto doSomething(type &&v) { return v.value(); }

doSomething(100) // deduction from arguments to doSomething<int>(100)
// will fail with error we cannot call value() on 100 (prvalue)
// but error is hard to understand and situation is a post factum


// with constrains
template <animation_interface type>
constexpr auto doSomething(type &&v) { return v.value(); }

doSomething(100) // does not fulfilled requirements for animation_interface (nice error)

// example 
class white_color_forever {
public:
    auto value() -> rgb { return {r(), g(), b()}; } 
    auto r() { return 0xff; }
    auto g() { return 0xff; }
    auto b() { return 0xff; }
    auto step() -> void {}
}

doSomething(white_color_forever{}); // fine, this is acceptable because 
// all exceptations are meet



There are requirements that must be fulfilled. Code does not compile if template parameter do not fulfill requirements. If you’re interested there is one of my use cases: a palette_converter_wrapper. Where I’m wrapping animation inside method forwarding class and overloading value() method. This code will play nice with any type that fulfill abstraction_interface requirements 🙂 So this is a static interface, that is what we’re waiting for.

Leave a Reply

Your email address will not be published. Required fields are marked *