std::remove_all_extents 源代码过多:为什么需要 3 个声明,而 2 个就足够了

问题描述 投票:0回答:1

当我查看来源时

template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_all_extents
    {typedef _Tp type;};
template <class _Tp> struct _LIBCPP_TEMPLATE_VIS remove_all_extents<_Tp[]>
    {typedef typename remove_all_extents<_Tp>::type type;};
template <class _Tp, size_t _Np> struct _LIBCPP_TEMPLATE_VIS remove_all_extents<_Tp[_Np]>
    {typedef typename remove_all_extents<_Tp>::type type;};

我的结论是,只需第一个和最后一个声明即可使此递归模板起作用。 为什么需要中定义?

我尝试仅用 2 个声明来实现相同的功能,并且它有效

c++ c++11 templates
1个回答
0
投票

例如,该中间模板可以帮助从未知边界的数组类型中删除范围。

示例:

template<template<class> class C, class T>
void foo(C<T>&) {
    static_assert(std::is_same_v<std::remove_all_extents_t<T>, char>);
}

template<class...> struct type;
template<> struct type<char[]> {};

int main(int argc, char *argv[]) {
    type<char[]> example;
    foo(example); // passes the assertion, but not without the middle template
}
© www.soinside.com 2019 - 2024. All rights reserved.