gpt4 book ai didi

C++:std::tuple_size/tuple_element 可以专门化吗?

转载 作者:IT老高 更新时间:2023-10-28 22:59:55 25 4
gpt4 key购买 nike

std::tuple_size 的特化和 std::tuple_element允许自定义类型?我想是的,但我想绝对确定,我找不到任何具体信息。

示例(省略了命名空间、成员函数和 get<I> 重载):

template <typename T, size_t N>
struct vector { T _data[N]; };

template<size_t I, typename T, size_t N>
constexpr T& get(vector<T,N>& vec) { return vec._data[I]; }

namespace std {
template<typename T, size_t N>
class tuple_size< vector<T,N> > : public std::integral_constant<size_t, N> { };
template<size_t I, typename T, size_t N>
class tuple_element< I, vector<T,N> > { public: using type = T; };
}

我需要将它用于结构化绑定(bind):

void f(vector<T,3> const& vec)
{
auto& [x,y,z] = vec;
// stuff...
}

最佳答案

用户定义类型的特化通常很好,而且一直都是。 N4606,[namespace.std]/1:

A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

对于 tuple_size ,原始模板的要求在[tuple.helper]/1中指定:

All specializations of tuple_size<T> shall meet the UnaryTypeTrait requirements with a BaseCharacteristic of integral_constant<size_t, N> for some N.

UnaryTypeTrait ,反过来,在 [meta.rqmts]/1:

A UnaryTypeTrait describes a property of a type. It shall be a class template that takes one template type argument and, optionally, additional arguments that help define the property being described. It shall be DefaultConstructible, CopyConstructible, and publicly and unambiguously derived, directly or indirectly, from its BaseCharacteristic, which is a specialization of the template integral_constant, with the arguments to the template integral_constant determined by the requirements for the particular property being described. The member names of the BaseCharacteristic shall not be hidden and shall be unambiguously available in the UnaryTypeTrait.

tuple_element的要求在 [tuple.helper]/6 和 [meta.rqmts]/3 中指定,但为了简洁起见,我不会在此处发布它们。可以说专攻确实是合法的……

关于C++:std::tuple_size/tuple_element 可以专门化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40584368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com