Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C++ reflection to automatically generate arithmetic operators?

As the reflection proposal just got accepted into the C++26 draft, I am wondering if the expected facilities could be used to automatically generate several arithmetic operators for a class?

For example, given an operator @= that could be +=, -=, *=, /=, ^=, &=, |=, <<=, >>=, would there be a way to generate all the operators using the following pattern?

// This is not legal C++, it is only for illustration purpose
template <class T>
struct myclass {
    using value_type = T;
    template <class U>
    requires requires(T& x, const U& y){{x @= y} -> std::same_as<T&>;}
    constexpr myclass& operator@=(const U& other) {
        value @= other;
        return *this;
    }
    T value;
};

I am wondering whether this could be achieved using the operator representation described in meta.reflection.operators?

like image 347
Vincent Avatar asked Sep 14 '25 12:09

Vincent


1 Answers

As the reflection proposal just got accepted into the C++26 draft, I am wondering if the expected facilities could be used to automatically generate several arithmetic operators for a class?

No. C++26 reflection only has one, very narrow generation facility: define_aggregate() lets us complete a class with a sequence of public, non-static data members. That's it so far. We have no way of injecting anything into a class currently being defined and we have no way of defining a class to include things like member functions, base classes, or even local type aliases.

You'd need the proposal for token sequence injection to accomplish this. At which point you could iterate over the enumerators in operators, figure out which ones of them are binary (probably an API that we'd need to add, but it's implementable by hand), and then you'd have to tokenize symbol_of that operator and just inject exactly the code you wrote. But that's for C++29.


But also something as straightforward as this can just be a C macro.

like image 173
Barry Avatar answered Sep 17 '25 01:09

Barry