我有这堂课
template <typename T>
class B{
T x;
public:
B(char c){
if(typeid(x)==typeid(char)) x=c;
else{
string h;
for(int i=0;i<10;i++) h.push_back(c);
x=h;
}
}
};
它是一个示例类,如果x的类型是char我想要x = c而如果x是一个字符串我想要x为[c] ^ 10
然后我尝试创建两个对象:
int main(){
B<string> a('f');
B<char> b('g');
}
当实例化i对象b时,编译器在第10行生成错误:
[Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'char' in assignment
我了解错误是由于您无法将字符串分配给char而造成的,但是无论如何我都需要完成任务,我该怎么办?
在C ++ 17之前的版本中,这似乎是最简单的可能性:
#include <string>
template<class T>
class B {
T x;
public:
B(char c);
};
template<>
B<char>::B(char c) : x(c) {}
template<>
B<std::string>::B(char c) : x(std::string(c,10)) {}
int main() {
B<char> a('a');
B<std::string> b('b');
//B<int> c('c'); // Linker error
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句