Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same class with 2 or 1 template parameter

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

like image 430
csiz Avatar asked Nov 06 '25 08:11

csiz


2 Answers

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.

like image 191
Daniel Earwicker Avatar answered Nov 08 '25 13:11

Daniel Earwicker


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.

like image 39
dirkgently Avatar answered Nov 08 '25 13:11

dirkgently