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

标签 c++ c++17

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/

相关文章:

c++ - 成员函数模板推导或其他方法让编译器知道如何调用函数

c++ - 如何在 C++ 矩阵 2D 的其他对角线上找到平行对角线反转

c++ - 基准可变参数模板函数调用

c++ - 为什么 as_const 的 const&& 重载被删​​除了?

c++ - 在构造函数中分配 std::string_view 类型是个好主意吗?

c++ - [c++/pointers] : having objects A and B (B has vector member, 存储指向 A 的指针),知道 A 是否可以检索指向 B 的指针?

c++ - 模板函数的奇怪输出的解释

c++ - 关键字 `this` 可以在类范围内使用吗?

c++ - 如何对 "duplicate"模板参数包进行扩展?

c++ - 为什么 g++ 允许返回不可复制的类?