查看 example implementation std::is_array
,它们具有以下代码:
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[]
与它在函数参数中的含义不同,它与指针的含义相同,对吗?
最佳答案
类型 T[]
是一个不完整的类型,已知它是一个数组,但此时大小(也是类型的一部分)未知。它可以在某些上下文中使用,在这些上下文中,您可能想要检查声明的变量是否为数组。虽然变量的类型仍然不完整,但 std::array
的第二个特化将不匹配,因为大小未知。
// test.h
struct Test {
static int data[];
};
// test.cpp
int Test::data[10];
只包含 header 但不可见 test.cpp
的 TU 可能想要测试 Test::data
是否为数组。
关于c++ - 模板特化中 T[N] 和 T[] 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20379635/