views:

230

answers:

3

How do I make a template specialization that takes 2 parameters versus the normal 1? I was building a pointer class and now I thought about extending to make an array but if I try something like this:

template<class T,int s> class pointer{};
template<class T> class pointer{};

class mama{};
int main(){
    pointer<mama> m;
}

It gives me an error. Template... redeclared with 1 parameter.

I need it specialized because pointer<mama,10> has size() and operator[] while pointer<mama> doesn't, it has operator-> and *.

+1  A: 

You can have a default value for the second parameter, perhaps something like this:

template <class T, int N=0>
class moo {
        T *foo;
public:
        moo() {
                if (N > 0) {
                        foo = new T[N];
                }
                else
                {
                        foo = new T;
                }
        }
};
Matt Kane
+2  A: 

You have class template redeclaration in your code which will lead to a compile-time error. You can have default template arguments and template template parameters.

template<class T,int s=10> class pointer{};

class mama{};
int main(){
    pointer<mama> m;
}

I need it specialized because pointer has size() and operator[] while pointer doesn't, it has operator-> and *.

It looks as if you need a different design for your class. I am not sure if template specialization is the way to go. From the looks of your problem, you really should be thinking of specializing based on traits.

dirkgently
+3  A: 

You could make a general template for the array case:

template <class TElem, int size = 0>
class pointer
{
    // stuff to represent an array pointer
};

Then a partial specialization:

template <class TElem>
class pointer<TElem, 0>
{
    // completely different stuff for a non-array pointer
};

By defining a specialized version for the case where size=0, you can actually give that a totally different implementation, but with the same name.

However, it might be clearer just to give it a different name.

Daniel Earwicker