假设我有一个模板类:
template <typename T>
class TC
{
...
};
和两个普通类:
class A
{
...
};
class B : public A
{
...
}
我可以显式实例化
TC<std::string> a(someString);
TC<int> a(5);
TC<A> a(someTestClassA);
TC<B> a(someTestClassB);
我想专门化模板类,以便它可以接受动态数组作为构造函数输入:
TC<int[]> a(new int[5]);
TC<int[]> b(a);
TC<B[]> c(new B[5]);
如何在我的构造函数中“读取”数组的大小?
特化(我认为)如下:
template <typename T>
class TC<T []>
{
public:
TC() : ptr(new T[n]) { }
T * ptr;
};
如何找出数字n?
编辑:
数字 n 在 main 函数中明确说明(因此,main 在编译时知道数字,但我如何告诉 TC[] 构造函数 n 是什么?)。
示例:
TC<int[]> a(new int[5]); // in the TC[] class constructor, n should be 5
我认为我正在寻找以下类似物(但对于类,即构造函数):
template <typename T, size_t N>
void f( T (&a)[N])
{
for(size_t i=0; i != N; ++i) a[i]=0;
}
最佳答案
"How to find out the number n?"
你不能。
使用 std::array<>
相反(或 std::vector<>
如果您在编译时不知道实际大小),它们旨在解决此类问题。
相关问答:Can someone explain this template code that gives me the size of an array?
您可能仍然不想自己实现它,这可能很难在特化中使用。
关于c++ - 模板类的特化(数组作为构造函数的输入)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30675036/