(为简洁起见,简化了代码) 我想创建一个带有模板 E A 的测试类以及一个只有 E 模板的测试类。当我完成此操作并尝试编译我的代码时,出现了以下错误:
error C2976: 'Test': too few template arguments
note: see declaration of 'Test'
error C2244: 'Test::Output': unable to match function definition to an existing declaration
error C2662: 'void Test::Output(void)': cannot convert 'this' pointer from 'Test' to 'Test &'
error C2514: 'Test': class has no constructors
#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;
}
最佳答案
类模板不能重载(函数模板可以),只能特化。如果你想要partial specialization , 应该是
template <typename E>
class Test<E, E>
{
...
};
和
template<typename E>
void Test<E, E>::Output()
{
...
}
并且在使用它时,您应该始终指定两个模板参数作为声明的主模板。即
Test<int, int> t(&a, &str); // the partial specialization will be used
编辑
Can I set the second template as a specific data type (such as
std::string
)? and useTest
likeTest<int, std::string>
是的。例如
template <typename E>
class Test<E, std::string>
{
...
};
和
template<typename E>
void Test<E, std::string>::Output()
{
...
}
关于c++ - 特定数据类型的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53022246/