Q:

How to implement a class with inner implementation dependent on template parameters?

I would like to write a class such that it's inner implementation depends on the template parameters. For instance (and I dont know if this is possible), say I could write something like:
MyClass<double,1> a;

and then this would be expanded at compile time as:
class MyClass{
double d;
public:
  MyClass(){d=0;}
};

and if instead I instantiated it as:
MyClass<double,2> a;

it would expand to:
class MyClass{
double d[3];
public:
  MyClass(){for(int i=0;i<3;i++) d[i]=0;}
};

Is this somehow possible using templates?
Please note that I dont want to have a double* d since I want to everything be static.
Thank you in advance.

A:

Yes, you can do this with partial specialization:
// base template must be defined first
template <class T, std::size_t N>
class MyClass {
    T d[N+1];
public:
    MyClass() { for (std::size_t i=0; i<N+1; i++) d[i] = 0; }
};

// then the partial specialization for N = 1:
template <class T>
class MyClass<T, 1> {
    T d;
public:
    MyClass() { d = 0; }
};

I'm a little uncertain about the base version--you show it as expanding to three items in the array when instantiated with the value 2, so that's what I've done above. I'd expect that to be the result from instantiating with the value 3 instead though. If that's what you really want, change both the N+1s to N.
Also note that at least for the specialized version, you'd normally want to use initialization instead of assignment, so the ctor would be more like:
MyClass() : d(0) {}

or (preferably):
MyClass() : d(T()) {}

You might also want to include a specialization for N=0 that wouldn't compile (or, about equivalently, use static_assert in the base template to assure that N>1).

