c++ - 如何为可以是字符或字符串的模板类实现方法?
问题描述
我有这门课
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,您可以使用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);
}
}
};
推荐阅读
- cmake - 在 Windows 10 上使用 HDF5:找不到 HDF5(缺少:HDF5_DIR)
- android - Android ADB:如何将多个文件推送到模拟器中?
- mongodb - 带有日期字段的mongodb查询嵌套数组
- arrays - Create a dictionary from an array but having an issue with key uniqness
- perl - 如何解析数据 HASH 格式的 SOAP 响应的输出?有关详细信息,请参见下面的代码
- coq - 在 Coq 中使用我自己的 == 运算符使用重写策略
- c++ - 如何读取 .txt 文件以在 C++ 中继承对象?
- python - Azure Linux Web 应用程序(startup.sh:未找到)
- compilation - 如何编译过时的内核(2.4.5)
- html - 我将网页的标题固定在顶部。那么为什么内容会在标题下进行呢?