什么可以使用std :: remove_extent?

时间:2015-07-25 06:58:34

标签: c++ c++11

我正在研究C ++ 11提供的新功能,我发现std::remove_extent

typedef std::remove_extent<int[24]>::type A; // A is int

但是除了通过从给定类型中删除维度从现有类型定义新类型之外,我无法找到它的用法。

有人能说出为什么C ++ 11引入了这个功能吗?使用它有什么好处吗?

2 个答案:

答案 0 :(得分:8)

在C ++标准本身中使用std::remove_extent就是一个很好的例子。

模板函数,用于创建智能指针std::unique_ptr

的对象
template <class T> unique_ptr<T> make_unique(size_t n);

返回以下表达式(20.8.1.4 unique_ptr creation p。#4)

unique_ptr<T>(new remove_extent_t<T>[n]())

考虑例如声明

auto p2 = std::make_unique<int[][10]>(2);

在这种情况下,make_unique需要在类型声明[]中删除指定为int[][10]的维度,并将其替换为[2]在新表达式中获取int[2][10]

答案 1 :(得分:2)

使用数组时,可能需要获取数组所包含的元素总数,包括子数组。这可以通过一些模板元编程来完成,方法是使用std::extentstd::rank以及std::remove_extent

template <class T, std::size_t N = std::extent<T>::value >
struct total_elements 
{
    using M_type = typename std::remove_extent<T>::type;
    static constexpr std::size_t value = N * total_elements< M_type >::value;
};

template <class T>
struct total_elements<T, 0> : std::integral_constant<std::size_t, 1> {};

Live example

如果您使用vector的{​​{1}},这可能会特别有用,因为无法保证存储是连续的:通过提供元素总数和1D vectors,您会得到那个。您还需要一些指针算法,使其表现得像多维一样,但在类中很容易抽象。

作为一个注释,标准并没有强制要求您使用它:如果您找到一个可能有用的地方,那就去吧。