【问题标题】:How to get integral type from a template type array如何从模板类型数组中获取整数类型
【发布时间】:2020-03-08 15:47:45
【问题描述】:

我正在尝试编写一个作用域指针类,该类在销毁后调用 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”

【问题讨论】:

    标签: c++ templates smart-pointers


    【解决方案1】:

    你想要的是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 是非法名称。所有以下划线开头并后跟大写字母的名称都保留用于实现。

    【讨论】:

    • 哇,谢谢,这真的很有帮助,我可以用 using/typedef 为该类型起别名吗?
    • @Denomycor 是的。你可以using BaseType = std::conditional_t&lt;_Dx, std::remove_extent_t&lt;type&gt;, type&gt;; ...; BaseType* m_ptr
    • @Denomycor 请注意,我已经更新了我的答案。不需要std::conditional_t
    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多