1

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;
}
AltairAC
  • 171
  • 1
  • 10
  • You can't read length/size of passed array. Not in templates, and not in any other construct. Pass it in as another variable to the function (constructor in this case) – Amit Jun 05 '15 at 20:15
  • in this line: TC a(new int[5]); , n is equal to 5 and is known at compile time, i.e. I explicitly state this number in the source code – AltairAC Jun 05 '15 at 20:16
  • 4
    The type of `new int[5]` is `int*`. There is no way to get the dimension 5 back from that expression. – aschepler Jun 05 '15 at 20:26
  • 1
    @AltairAC _"The number n is explicitly stated in the main function"_ You'd still need a specialization for `int[5]` (and so essentially for every possible size), it's actually not the same as `int[]`. – πάντα ῥεῖ Jun 05 '15 at 21:53

2 Answers2

3

"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.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
3

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.

Barry
  • 286,269
  • 29
  • 621
  • 977