Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Introducing KDBindings

Reactive Programming and Data Binding in C++

#include "kdbindings/binding.h"
#include "kdbindings/property.h"
#include "kdbindings/signal.h"

#include <iostream>

using namespace KDBindings;

class Image
{
public:
    const int bytesPerPixel = 4;
    Property<int> width { 800 };
    Property<int> height { 600 };
    const Property<int> byteSize = makeBoundProperty(bytesPerPixel * width * height);
};

int main()
{
    Image img;
    std::cout << "The initial size of the image = "
              << img.byteSize.get() << " bytes" << std::endl;

    img.byteSize.valueChanged().connect([] (const int &newValue) {
        std::cout << "The new size of the image = " << newValue << " bytes" << std::endl;
    });

    img.width = 1920;
    img.height = 1080;

    return 0;
}
The initial size of the image = 1920000 bytes
The new size of the image = 4608000 bytes
The new size of the image = 8294400 bytes
static BindingEvaluator evaluator;
...
const Property<int> byteSize = makeBoundProperty(evaluator, bytesPerPixel * width * height);
img.width = 1920;  // Does not trigger an evaluation of the binding
img.height = 1080; // Nor does this

evaluator.evaluateAll(); // This does!
The initial size of the image = 1920000 bytes
The new size of the image = 8294400 bytes
BindingEvaluator evaluator;

Property<int> a { 2 };
Property<int> b { 7 };
Property<int> c { 3 };
Property<int> d { 4 };
auto e = makeBoundProperty(evaluator, (a + b) * (c + d)); // e is a Property<int> too.

Property<float> x { -7.5f };
Property<float> y { 2.35f };
auto z = makeBoundProperty(evaluator, y + abs(sin(x)));
struct node_paraboloid
{
    template <typename T>
    auto operator()(T&& x, T&& y) const // Use as many arguments as you like
    {
        // Do something useful or call a library function...
        return x * x + y * y;
    }
};
KDBINDINGS_DECLARE_FUNCTION(paraboloid, node_paraboloid {})

auto evaluator = BindingEvaluator{};
Property<int> x { -2 };
Property<int> y { 3 };
auto z = makeBoundProperty(evaluator, paraboloid(x, y));
Property<int> a { 10 };
Property<int> b { 14 };
const Property<int> x = makeBoundProperty(defaultEvaluator(), 2 * (a + b));
...
x = 35; // Compile-time error!
Property<int> a { 10 };
Property<int> b { 14 };
Property<int> x = makeBoundProperty(defaultEvaluator(), 2 * (a + b));
...
x = 35; // Throws a ReadOnlyProperty exception

About KDAB


6 Comments

8 - Jan - 2022

Vadim Peretokin

13 - Jan - 2022

Sean Harmer

10 - Jan - 2022

Foster Brereton

13 - Jan - 2022

Sean Harmer

26 - Mar - 2024

FeRDNYC (Frank Dana)

15 - May - 2024

Sean Harmer

SeanHarmer

Sean Harmer

Managing Director KDAB UK

Learn Modern C++

Learn more