首页 > 解决方案 > 如何为可以是字符或字符串的模板类实现方法?

问题描述

我有这门课

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++classtemplates

解决方案


使用 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);
        }
    }
};

推荐阅读