模板特化中T [N]和T []之间的差异?

时间:2013-12-04 15:42:12

标签: c++ templates template-specialization

查看std::is_array的{​​{3}},他们有以下代码:

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[]与函数参数中的{{1}}不一样,它与指针的意思相同?

1 个答案:

答案 0 :(得分:9)

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

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

仅包含标题但不具有test.cpp可见性的TU可能需要测试Test::data是否为数组。