AltairAC
AltairAC

Reputation: 171

Specialization of a template class (array as input for the constructor)?

Let's say that I have a template class:

template <typename T>
class TC
{
...
};

and two normal classes:

class A
{
...
};

class B : public A
{
...
}

and I can explicitly instantiate

TC<std::string> a(someString);
TC<int> a(5);
TC<A> a(someTestClassA);
TC<B> a(someTestClassB); 

and I want to specialize the template class so that it can accept an dynamic array as constructor input:

TC<int[]> a(new int[5]);
TC<int[]> b(a);
TC<B[]> c(new B[5]);

How do I "read" the size of the array inside my constructor?

The specialization would be (I think) as follows:

template <typename T>
class TC<T []>
{
    public:
    TC() : ptr(new T[n]) { }

    T * ptr;
};

How to find out the number n?

EDIT:

The number n is explicitly stated in the main function (so, main knows the number at compile time but how do I tell the TC[] constructor what n is?).
Example:

TC<int[]> a(new int[5]); // in the TC[] class constructor, n should be 5

I think that I am looking for an analogon of the following (but for classes i.e. constructors):

template <typename T, size_t N> 
void f( T (&a)[N])
{
    for(size_t i=0; i != N; ++i) a[i]=0;
}

Upvotes: 1

Views: 356

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"How to find out the number n?"

You cannot.

Use std::array<> instead (or std::vector<> if you don't know the actual size at compile time), they were designed to solve these kind of problems.


Related Q&A: Can someone explain this template code that gives me the size of an array?

You'd still may not want to implement this yourself, that could get hard to be used in specializations.

Upvotes: 3

Barry
Barry

Reputation: 303870

You could partially specialize on a raw-array of known size:

template <typename T, size_t N>
class TC<T[N]>
{
public:
    TC() : ptr(new T[N]) { }
private:
    T* ptr;
};

TC<int[4]> dynamic_array_of_4_ints;

Though this is sort of halfway between std::array<T, N> a and std::vector<T> v(N), and likely worse than both.

Upvotes: 3

Related Questions