c++ - c++中的模板特化定义
问题描述
我声明了一个模板专业化template <> class Component<NullType, NullType, NullType, NullType>
,并定义了它。
我的问题是当我减少
NullType
in Component 时,p->Initialize()
总是会成功并被调用。这个功能是什么?另一个问题是为什么我不能同时定义
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;
}
解决方案
我的问题是当我减少
NullType
in 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()
?
如上所述,它们被认为是相同的,您将收到重新定义错误。
推荐阅读
- javascript - 使用 Javascript 简化 HTML 表格
- html - 如何从动态 Web 元素 [id] 获取数据并将该数据动态写入 excel 中的输入数据的相邻单元格
- ruby-on-rails - 在 Ruby on Rails 中使用 :path 理解路由
- typescript - 在 HTML 脚本标签中的 Typescript 中调用函数
- java - 将 SOAP XML 字符串转换为对象或仅读取其内容
- python - 如何使用 Telethon 从电报消息中获取图像字节
- go - NATS 订阅后只接收消息
- woocommerce-rest-api - 产品 ID 的 woocommerce REST API 评级
- android - IP地址范围的网络安全配置?
- android - 如何将可渲染的小节点放置在可渲染的较大节点的相同位置?