如何编写一个包装器词法强制转换函数来实现如下行:
int value = lexical_cast<int> (string)
我对编程很陌生,想知道我们如何编写这个函数。我不知道怎么找出模板。我们也可以为double写一个包装函数吗?像
double value = lexical_cast2<double> (string)
? ?
如您在示例中所述:
#include <sstream>
template <class Dest>
class lexical_cast
{
Dest value;
public:
template <class Src>
lexical_cast(const Src &src) {
std::stringstream s;
s << src;
s >> value;
}
operator const Dest &() const {
return value;
}
operator Dest &() {
return value;
}
};
包含错误检查:
template <class Src>
lexical_cast(const Src &src) throw (const char*) {
std::stringstream s;
if (!(s << src) || !(s >> value) || s.rdbuf()->in_avail()) {
throw "value error";
}
}
你可以尝试这样做:
#include <sstream>
#include <iostream>
template <class T>
void FromString ( T & t, const std::string &s )
{
std::stringstream str;
str << s;
str >> t;
}
int main()
{
std::string myString("42.0");
double value = 0.0;
FromString(value,myString);
std::cout << "The answer to all questions: " << value;
return 0;
}
如果这不是一个练习,如果您的目标只是将字符串转换为其他类型:
如果你使用的是c++ 11,有新的转换函数
所以你可以这样写
std::stoi -> int
std::stol -> long int
std::stoul -> unsigned int
std::stoll -> long long
std::stoull -> unsigned long long
std::stof -> float
std::stod -> double
std::stold -> long double
http://www.cplusplus.com/reference/string/如果不是c++ 11,可以使用
int i = atoi( my_string.c_str() )
double l = atof( my_string.c_str() );
您可以简单地使用这个头。然后写to<std::string>(someInt)
或to<unsigned byte>(1024)
。第二部分将抛出并告诉您您正在做坏事。