【发布时间】:2014-12-17 14:32:41
【问题描述】:
我想写自己的转换函数&重用 boost::lexical_cast();因此我重载了 boost::lexical_cast() 函数。毕竟,为了同样的目的,boost::conversion::try_lexical_convert() 被添加到库中。
我的程序有效,Overloaded lexical_cast() 在前两种情况下被调用,因为这两个调用都是在本地进行的。在第三种情况下,父函数 boost::lexical_cast() 被调用,因为对 boost::lexical_cast() 的调用是通过 parse_date() 路由的。
我想通过我的 lexical_cast() 函数处理所有转换。即每当调用 boost::lexical_cast() 时,我的重载函数都会被调用。
有什么办法,可以写出这样的全局lexical_cast()函数处理程序?
另外,请建议我们如何自定义全局处理程序,使其只能在指定的少数 POD 和 boost 数据类型中调用。
#include <iostream>
#include <string>
#include <exception>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
namespace boost
{
template<typename T>
T lexical_cast(const std::string &str)
{
if(str.empty()) //handle preconditions here, some custom logic
return T();
T result;
if (!conversion::try_lexical_convert(str, result))
throw bad_lexical_cast();
return result;
}
}
using namespace std;
using namespace boost;
using namespace boost::posix_time;
using namespace boost::gregorian;
int main(int ac, char* av[])
{
try
{
//1.
auto p1_ = lexical_cast<int>(std::string(""));
std::cout << "p1 = " << p1_ << std::endl; //displays 0, which is correct. calls overloaded lexical_cast()
//2.
auto p2_ = lexical_cast<int>(std::string("1"));
std::cout << "p2 = " << p2_ << std::endl; //displays 1, which is correct. calls overloaded lexical_cast()
//3.
std::locale locale_;
boost::date_time::format_date_parser<boost::gregorian::date, char> parser_("", locale_);
boost::date_time::special_values_parser<boost::gregorian::date, char> svp_;
boost::gregorian::date date_ = parser_.parse_date("2014-Dec-17", "%Y-%b-%d", svp_); //calls boost::lexical_cast(), but I want call to overloaded lexical_cast() instead.
}
catch(std::exception& e)
{
cout << e.what() << "\n";
return 1;
}
return 0;
}
【问题讨论】: