Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specialize Class for all other types

Assume having MyContainer template class, like:

template <typename T>
class MyContainer {
public:
    T *content;
    void *data;
};

Now, assume having MyContetWithData class as well, which already contains the void *data field, hence there is no need to duplicate it in MyContainer, but, all other types yet need said field, only MyContetWithData does not need it.

How can we specialize MyContainer so that void *data; is removed from MyContainer if T is of type MyContetWithData, but keep said field for all other types?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply provide an explicit specialization for MyContetWithData as shown below:

//primary template for all other types as before
template <typename T>
class MyContainer {
public:
    T *content;
    void *data;
};
//explicit specialization for MyContetWithData without data
template <> class MyContainer<MyContetWithData> 
{ 
    MyContetWithData *content;
};

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading