【发布时间】:2020-04-24 18:39:20
【问题描述】:
我是 C++ 模板的新手。我在将模板化成员对象转换为 std::string 时遇到问题。我下面的代码无法打印字符'c'(在我的机器上打印'R'),我找不到让它工作的方法。使用 char 作为类型 T 时有没有办法做到这一点?
#include <iostream>
#include <string>
template<class T>
class A {
public:
T t;
A(T t1):t{t1}{};
std::string toString(){
return "" + static_cast<char>(t);
};
};
using namespace std;
int main()
{
A<char> a{'c'};
cout << a.toString() <<"\n";
return 0;
}
【问题讨论】:
-
你打算为
T使用除char之外的其他类型吗?
标签: c++ string templates char type-conversion