首页 > 解决方案 > c++中的模板特化定义

问题描述

我声明了一个模板专业化template <> class Component<NullType, NullType, NullType, NullType>,并定义了它。

  1. 我的问题是当我减少NullTypein Component 时,p->Initialize()总是会成功并被调用。这个功能是什么?

  2. 另一个问题是为什么我不能同时定义bool Component<NullType, NullType, NullType>::Initialize()两者bool Component<NullType, NullType, NullType, NullType>::Initialize()

#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;
}

标签: c++templates

解决方案


我的问题是当我减少NullTypein Component

然后将使用主模板中指定的默认参数,即NullType。作为效果,

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

与以下相同:

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

另一个问题是为什么我不能同时定义bool Component<NullType, NullType, NullType>::Initialize()两者bool Component<NullType, NullType, NullType, NullType>::Initialize()

如上所述,它们被认为是相同的,您将收到重新定义错误。


推荐阅读