c++ - 允许模板化类的结构化绑定(bind)

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

所以我有一个小类,我想在其中添加结构化绑定(bind)支持。 但是我无法弄清楚如何使用我的模板化类来专门化 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 ';'

是否有可能允许模板化类具有结构化绑定(bind),或者我是否遗漏了什么?

最佳答案

事实证明,我的 tuple_size 特化需要有一个我忽略的主体。

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

感谢@BoPersson 指出这一点!

关于c++ - 允许模板化类的结构化绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47990899/

相关文章:

c++ - 直接列表初始化和复制列表初始化之间的区别

c++ - shared_ptr 的 unordered_set 找不到它存储的等效对象

c++ - 在 Windows 中使用 gmail 作为 smtp 中继器在 c++ 中发送邮件

c++ - 当 template<typename, value...> 时强制特定重载

c++ - C++17 std::to_chars 是否添加了一个空终止符?

c++ - 参数列表中间的可变模板参数

C++函数映射实现

c++ - Qt C++串口类的继承

c++ - 如果输入非整数,如何防止无限循环?

c++ - 在运行时通过参数更改通过另一个模块回调(重新实例化)一个模块