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