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

Gug*_*tra 1 c++ templates class

我有这门课

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)

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

Jar*_*d42 7

使用 C++17,你可以使用if constexpr

template <typename T>
class B
{
    T x;
public:
    explicit B(char c)
    {
        if constexpr (std::is_same_v<T, char>) {
            x = c;
        } else {
            // static_assert(std::is_same_v<T, std::string>);
            x = std::string(10, c);
        }
    }
};
Run Code Online (Sandbox Code Playgroud)