App*_*ker 0 c++ string generics types casting
我有这门课:
template<typename T> class Parser
{
public:
Parser() : count(0) {}
virtual void parse(const string&);
void get_token(void);
private:
T result;
char token;
string expression;
int count;
};
Run Code Online (Sandbox Code Playgroud)
现在这个类不是通用的,如果result有人说,a double,我会用这种方法来检测数字.
while((strchr("1234567890.",token))
{
/* add token to a "temp" string */
/* etc. etc. */
}
result = atof(temp.c_str());
Run Code Online (Sandbox Code Playgroud)
但既然result是通用的,我不能像使用任何方法atof和atoi等.
我该怎么办?
Boost内置了此功能:
#include <boost/lexical_cast.hpp>
void Parser<T>::get_token() {
std::string token = ...;
result = boost::lexical_cast<T>(token);
}
Run Code Online (Sandbox Code Playgroud)
根据需要添加异常处理.
或者,也许你不想出于某种原因使用Boost:
void Parser<T>::get_token() {
std::string token = ...;
std::stringstream ss;
ss << token;
ss >> result;
}
Run Code Online (Sandbox Code Playgroud)
ss根据需要检查错误状态.
可以在这个相关问题上找到更广泛的答案,尽管它只是int具体讨论.
| 归档时间: |
|
| 查看次数: |
1935 次 |
| 最近记录: |