允许模板化类的结构化绑定

时间:2017-12-27 10:53:39

标签: c++ templates c++17 specialization structured-bindings

所以我有一个小课程,我想添加结构化绑定支持。 但是,我无法弄清楚如何使用模板化的类来专门化std::tuple_elementstd::tuple_size。 这是我的尝试:

template<typename... Cmps>
struct CmpGroup
{
    std::array<void*, sizeof...(Cmps)> cmps;

    template<typename C>
    C& get()
    {
        constexpr int index = GetIndexInPack<C, Cmps...>::value;
        static_assert(index != -1);
        return *static_cast<C*>(index);
    }

    template<size_t I>
    auto& get()
    {
        static_assert(I < sizeof...(Cmps));
        using CmpType = typename GetTypeInPack<I, Cmps...>::type;
        return *static_cast<CmpType*>(cmps[I]);
    }
};

namespace std
{
    template<typename... Types>
    struct tuple_size<CmpGroup<Types...>> : public integral_constant<size_t, sizeof...(Types)>;

    template<std::size_t N, typename... Types>
    struct tuple_element<N, CmpGroup<Types...>> {
        //got this from: https://blog.tartanllama.xyz/structured-bindings/
        using type = decltype(std::declval<CmpGroup<Types...>>().template get<N>());
    };
}

(为清楚起见,我省略了一些具体的实施内容,可以找到完整的代码段here

但是这会导致tuple_size特化产生编译错误:error C2143: syntax error: missing ',' before ';'

甚至可以允许模板化的类具有结构化绑定,还是我错过了什么?

1 个答案:

答案 0 :(得分:3)

事实证明,我的tuple_size专业化需要有一个我忽略的身体。

template<typename... Types>
struct tuple_size<CmpGroup<Types...>> : public integral_constant<size_t, sizeof...(Types)>{};
------------------------------------------------------------------------------------------^^

感谢@BoPersson指出这一点!

相关问题