template specialization define in c++

Advertisements

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?

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

Leave a ReplyCancel reply