小编Gug*_*tra的帖子

我如何为可以是字符或字符串的模板类实现方法?

我有这门课

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;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

它是一个示例类,如果 x 的类型是 char 我想要 x=c 而如果 x 是一个字符串我想要 x 是 [c]^10

然后我尝试创建两个对象:

int main(){
    B<string> a('f');
    B<char> b('g');     
}
Run Code Online (Sandbox Code Playgroud)

当 i 对象 b 被实例化时,编译器在第 10 行产生一个错误:

[Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'char' in assignment
Run Code Online (Sandbox Code Playgroud)

我知道错误来自于您无法将字符串分配给字符的事实,但无论如何我都需要完成任务,我该怎么做?

c++ templates class

1
推荐指数
1
解决办法
65
查看次数

标签 统计

c++ ×1

class ×1

templates ×1