mardi 5 octobre 2021

c++11 way of returning an array of unknown number of elements

I would like to implement this function (or a similar one, see the requirements below) in C++11:

template<typename... ARGS>
constexpr std::array<const typename std::common_type<ARGS...>::type, sizeof...(ARGS)> asConstArray(ARGS&&... args)
{
    return {std::forward<ARGS>(args)...};
}

static constexpr auto getRawBindings()
// HERE          ^- C++14, deduced to std::array<const BindingInfo, 2> in this case
{
    return asConstArray(
        DEF_BINDING(int, stateProp, stateParam), //BindingInfo constexpr object
        DEF_BINDING(float, areaProp, areaParam)  //BindingInfo constexpr object
        //(...)
    );
}

As you see I would like to introduce a macro-based interface (it is necessary, it does a lot of other Qt related magic).

DEF_BINDING returns a constexpr object of an user-defined struct (BindingInfo - it contains a few const char* and size_t members, it can be replaced with any struct or template that can contain the same).

I don't want to force the programmer to count the bindings manually because it would be inconvenient. The solution above is the closest I could figure out, but I would like to solve the followings in C++11:

  1. Needs to return an array of elements (array like, using std::array is not a must-have)
  2. Must be compile time
  3. The items must be defined only once (do not want to enumerate the array elements twice)
  4. Must be header-only (static constexpr member defined in the cpp file cannot work, non-ODR regulated use can work)
  5. The array-size must be auto-deduced

The solution can use any kind of C++11 magic. I hope we can figure out something :)

Aucun commentaire:

Enregistrer un commentaire