如何从模板类型数组中获取整数类型

How to get integral type from a template type array

我正在尝试编写一个作用域指针 class,它在被销毁后调用 delete。我意识到我需要检查我的指针是否指向一个数组,所以我可以调用正确的删除。 从 std::unique_ptr 中获得灵感,我使用 type_traits 来检查保存类型指针的模板参数是否为数组:

template <typename type, bool _Dx = std::is_array<type>::value>
    class scoped_ptr {
    private:
        type* m_ptr;
    //...
    };

template <typename type>
    class scoped_ptr<type, true> {};

但是如果我的模板参数类型是 "int[]" 代码无效,因为我不能有一个 "int[]* m_ptr" 我怎么解决这个问题?我如何传递 int[] 参数并获得 "int* m_ptr"

你要的是std::remove_extent。如果你给它一个数组,它会给你元素类型,否则它只会给你你给它的类型。看起来像

template <typename type, bool _Dx = std::is_array<type>::value>
class scoped_ptr {
private:
    std::remove_extent_t<type>* m_ptr;
//...
};

另请注意,_Dx 是一个非法名称。所有以下划线开头且后跟大写字母的名称均保留用于实现。