c++ 使用std::tuple的类继承项自定义std::get

polkgigr  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(132)

I have created a class than inherit from std::tuple as:

template<class, class>
struct tuple_prepend;

template<class T, class ...Ts>
struct tuple_prepend<T, std::tuple<Ts...>>
{
    using type = std::tuple<T, Ts...>;
};

template<class ...Ts>
struct tuple_optional_impl;

template<class T, class ...Ts>
struct tuple_optional_impl<T, Ts...>
{
    using type = typename tuple_prepend<std::optional<T>, typename tuple_optional_impl<Ts...>::type>::type;
};

template<class T>
struct tuple_optional_impl<T>
{
    using type = std::tuple<std::optional<T>>;
};

template<class ...Ts>
struct tuple_optional;

template<class ...Ts>
struct tuple_optional<std::tuple<Ts...>>
{
    using type = typename tuple_optional_impl<Ts...>::type;
};

template<class ...Ts>
class Tuple : public tuple_optional<std::tuple<Ts...>>::type
{
};

tuple_optional : convert an std::tuple<T> into std::tuple<std::optional<T>> and have the same behavior with Ts... .
I would like to make a custom std::get<T> to handle Tuple , I have this implementation:

namespace std
{
    template<class T, class ...Ts>
    std::optional<T> get(Tuple<Ts...> &_tuple) noexcept
    {
        return std::get<std::optional<T>>(static_cast<tuple_optional<std::tuple<Ts...>>::type>(_tuple));
    }
}

But the static_cast generate this error:
error C2100: illegal indirection
message : see the reference at the instanciation of model: 'std::optionalecs::comp::HitBox std::getecs::comp::HitBox,ecs::comp::Stat,ecs::comp::Position,ecs::comp::HitBox,ecs::comp::Rotation,ecs::comp::Id(Tupleecs::comp::Stat,ecs::comp::Position,ecs::comp::HitBox,ecs::comp::Rotation,ecs::comp::Id &) noexcept' at compilation
I don't wan't to use an alias or erase the inheritance.

dgtucam1

dgtucam11#

你不需要这些。

template<class ...Ts> using Tuple = std::tuple<std::optional<Ts>...>;

相关问题