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

template specialization define in c++

I declared a template specialization template <> class Component<NullType, NullType, NullType, NullType>, and defined it.

  1. My question is when I reduce the NullType in Component, p->Initialize() will always success and is called. What is this feature?

  2. Another question is why I cannot define both bool Component<NullType, NullType, NullType>::Initialize() and bool Component<NullType, NullType, NullType, NullType>::Initialize() at the same time?

    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

#include <iostream>

using namespace std;

class NullType {};

template <typename M0 = NullType, typename M1 = NullType,
          typename M2 = NullType, typename M3 = NullType>
class Component {
 public:
  bool Initialize();
};

template <>
class Component<NullType, NullType, NullType, NullType> {
 public:
  bool Initialize();
};

bool Component<NullType, NullType, NullType>::Initialize() {
    cout<<"Hello World3";
    return true;
}

// bool Component<NullType, NullType, NullType, NullType>::Initialize() {
//     cout<<"Hello World4";
//     return true;
// }

int main()
{
    auto p = new Component<>();
    p->Initialize();
    return 0;
}

>Solution :

My question is when I reduce the NullType in Component

Then the default argument specified in primary template, i.e. NullType will be used. As the effect,

bool Component<NullType, NullType, NullType>::Initialize() {

is just same as:

bool Component<NullType, NullType, NullType, NullType>::Initialize() {

Another question is why I cannot define both bool Component<NullType, NullType, NullType>::Initialize() and bool Component<NullType, NullType, NullType, NullType>::Initialize() at the same time?

As explained above, they’re considered as the same and you’ll get a redefinition error.

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