【问题标题】:Difference between T[N] and T[] in template specializations?模板专业化中 T[N] 和 T[] 之间的区别?
【发布时间】:2013-12-04 15:42:12
【问题描述】:

查看std::is_array的example implementation,它们的代码如下:

template<class T>
struct is_array<T[]> : std::true_type {};

template<class T, std::size_t N>
struct is_array<T[N]> : std::true_type {};

什么时候匹配 T[] 特化而不是 T[N] 特化?为什么需要两个?我认为这个T[] 与它在函数参数中的含义不同,它与指针的含义相同,对吧?

【问题讨论】:

    标签: c++ templates template-specialization


    【解决方案1】:

    T[] 类型是一个不完整的类型,已知它是一个数组,但此时大小(也是类型的一部分)未知。它可以在某些上下文中使用,在这些上下文中,您可能想要检查声明为这样的变量是否为数组。虽然变量的类型仍然不完整,但 std::array 的第二个特化将不匹配,因为大小未知。

    // test.h
    struct Test {
       static int data[];
    };
    // test.cpp
    int Test::data[10];
    

    仅包含标头但不可见 test.cpp 的 TU 可能想要测试 Test::data 是否为数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 2011-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      相关资源
      最近更新 更多