c++ - 特定数据类型的模板类
问题描述
(为了简单起见,代码被简化了)我想创建一个带有模板 EA 的测试类,以及一个只有 E 模板的测试类。当我完成此操作并尝试编译我的代码时,出现以下错误:
错误 C2976:“测试”:模板参数太少
注意:参见“测试”的声明
错误 C2244:“Test::Output”:无法将函数定义与现有声明匹配
错误 C2662:“void Test::Output(void)”:无法将“this”指针从“Test”转换为“Test &”
错误 C2514:“测试”:类没有构造函数
#include <iostream>
#include <string>
template <typename E, typename A>
class Test
{
public:
Test(E *e = nullptr, A *a = nullptr) : a(e), b(a) {}
void Output();
private:
E * a;
A *b;
};
template <typename E, typename A>
void Test<E, A>::Output()
{
std::cout << " " << *a << " " << *b;
}
template <typename E>
class Test
{
public:
Test(E *e = nullptr, std::string *a = nullptr) : a(e), b(a) {}
void Output();
private:
E * a;
std::string *b;
};
template<typename E>
void Test<E>::Output()
{
std::cout << *a << *b;
}
int main()
{
int a = 10;
std::string str = "hi";
Test<int> t(&a, &str);
t.Output();
return 0;
}
解决方案
类模板不能重载(函数模板可以),而只能是特化的。如果你想要部分专业化,它应该是
template <typename E>
class Test<E, E>
{
...
};
和
template<typename E>
void Test<E, E>::Output()
{
...
}
并且在使用它时,您应该始终指定两个模板参数作为被声明的主模板。IE
Test<int, int> t(&a, &str); // the partial specialization will be used
编辑
我可以将第二个模板设置为特定的数据类型(例如
std::string
)吗?Test
并使用Test<int, std::string>
是的。例如
template <typename E>
class Test<E, std::string>
{
...
};
和
template<typename E>
void Test<E, std::string>::Output()
{
...
}
推荐阅读
- javascript - 即使在插入组件后,如何显示带有样式组件图标的图标?(盖茨比)
- oauth-2.0 - 使用 IdentityServer 4 中的授权代码流保护公共 API
- javascript - 我们可以在 github 操作中缓存纱线全局变量吗
- sql - 结合两个查询 Oracle SQL
- c - 从waitpid返回的“终止状态”和“结束状态”有什么区别?
- jar - 使用 SAP BO API 重新触发计划实例?
- python - 如何从我的空列表中删除逗号和方括号?
- html - Angular9-MatDatePicker:无法绑定到“ngModel”,因为它不是“输入”的已知属性
- aws-lambda - 为 SAM 中的函数事件引用外部定义的 API
- java - 我如何在java中使用c#的相同sha512验证