【问题标题】:C++ template parameter T(*)[] [duplicate]C ++模板参数T(*)[] [重复]
【发布时间】:2017-06-25 13:53:25
【问题描述】:

这是 Visual Studio 2017 社区版中std::default_delete 的源代码。

template<class _Ty>
struct default_delete<_Ty[]>
{
    // default deleter for unique_ptr to array of unknown size
    constexpr default_delete() _NOEXCEPT = default;

    template<class _Uty, class = typename enable_if<is_convertible<_Uty(*)[], _Ty(*)[]>::value, void>::type>
    default_delete(const default_delete<_Uty[]>&) _NOEXCEPT
    {
        // construct from another default_delete
    }

    template<class _Uty, class = typename enable_if<is_convertible<_Uty(*)[], _Ty(*)[]>::value, void>::type>
    void operator()(_Uty *_Ptr) const _NOEXCEPT
    {
        // delete a pointer
        static_assert(0 < sizeof (_Uty), "can't delete an incomplete type");
        delete[] _Ptr;
    }
};

我注意到 is_convertible&lt;_Uty(*)[], _Ty(*)[]&gt; 内部数组特化中的模板参数 _Uty(*)[]_Ty(*)[]

如果它是_Ty(&amp;)[],那么我肯定会知道它是对类型为_Ty 的数组的引用,正如post 所涵盖的那样,但对于_Ty(*)[] 的含义一无所知。 如果有人能阐明这个奇异的模板参数,那将非常有帮助。

编辑: 非常感谢你们!我设法安装了一个带有指向数组的指针的函数。

template <typename T>
T* func0(T(*parr)[], std::initializer_list<T> args)
{
    int i = 0;
    for (T arg : args)
        (*parr)[i++] = arg;
    return *parr;
}

template <typename T, unsigned S>
T* func1(T(*parr)[S], std::initializer_list<T> args)
{
    int i = 0;
    for (T arg : args)
        (*parr)[i++] = arg;
    return *parr;
}

int main(void)
{
    std::string strs[5];
    //std::string* pstrs = func1(&strs, {"133", "233", "333", "433", "533"}); // Not working! Cannot deduce template param T from args
    std::string* pstrs = func1<std::string, 5>(&strs, {"133", "233", "333", "433", "533"}); // Works fine!
    //std::string* pstrs = func0<std::string, 5>(&strs, {"133", "233", "333", "433", "533"}); // Not working! No instance of function template match
    return 0;
}

我想知道为什么模板参数 T 不能从传递给 func1 的参数中推断出来? 还有,T(*parr)[S]中的尺寸信息S好像是必须的。

【问题讨论】:

  • 当然是指向_Ty 类型数组的指针。例如。如果您将&amp; 运算符的地址应用于对_Ty 类型数组的引用(您已经知道其存在),这就是您所得到的。
  • T(*)[] 只是一个指向未指定数量的 T 对象数组的指针。令人困惑的一点是测试它的可转换性,因为指向一种类型的数组的指针(或引用)不会转换为其他数组的指针(或引用)。我constconst的转换仍然是允许的。

标签: c++ arrays templates


【解决方案1】:

_Ty(&)[] 是对 C 样式数组的引用。

_Ty(*)[] 是指向 C 风格数组的指针。

【讨论】:

  • 不完整 C 样式数组。
  • 在使用关键字pointer to C-style array 进行谷歌搜索后,我发现了一个很好的post 用法。作者只在他的代码示例中展示了它的用法,没有任何解释或参考。
  • @StoryTeller 谢谢你我的救命恩人!我设法使用关键字incomplete C-style array 找到了大量信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多