veselink1 / refl-cpp

Static reflection for C++17 (compile-time enumeration, attributes, proxies, overloads, template functions, metaprogramming).
https://veselink1.github.io/refl-cpp/md__introduction.html
MIT License
1.05k stars 76 forks source link

Q: Implementing a member attribute for "Default value" to use in ctors #82

Open FoamScience opened 10 months ago

FoamScience commented 10 months ago

I'd like to maintain a certain level of verbosity when it comes to important class members. Currently, I'm writing members as:

class MyClass
{
    struct d {
        static constexpr std::string_view name_ = "d";
        static constexpr std::string_view descritption_ = "d";
        static const std::vector<double> default_;
        std::vector<double> v;
    } d;
};

This works, and with some macros, I can make it clutter-free; to some extent.

I was wondering if it is possible to write a reflected attribute to the member so it can be used as:

// d here is just a std::vector
REFL_AUTO(
    type(MyClass),
    field(d, defaulted<std::vector<double>>({2, 3.5, 10})),
)

And in constructor:
```cpp
// Use reflected default in ctor
MyClass::MyClass() : d(getDefault<MyClass>("d")){}

While this works for literal types; I don't seem to be able to make it work for types which require dynamic memory allocation. Any pointers as to what to do to make this work? Having the reflection system take care of this will be amazing.

Here is my attempt at a defaulted attribute which works for literal types: https://godbolt.org/z/44KG4YbxT