假设我有一个
boost::variant<std::string, int> myVariant;
在这个对象中,我保存来自数据库的数据,这些数据通常是整数或文本,但有时是以文本形式存储在数据库中的时间。所以我想知道我是否可以创建一个访问者,当访问带有字符串的变体对象时,它会返回一个“tm”类型的结构。像这样的东西:
class timeVisitor : public boost::static_visitor<boost::shared_ptr<tm> >
{
public:
boost::shared_ptr<tm> operator()(string &str) const
{
boost::shared_ptr<tm> dst(new tm());
strptime(str.c_str(), "%Y-%m-%d", dst.get());
return dst;
}
};
然后为了使用它:
boost::shared_ptr<tm> result = boost::apply_visitor( timeVisitor(), myVariant );
问题是,我不想在访问者中创建 tm 结构并弄乱一些共享指针和东西。我更喜欢给访问者一个已经创建的,并且在里面只是为了被初始化。类似于(在使用意义上):
tm result;
int returnCode = boost::apply_visitor( timeVisitor(result), myVariant );
访问者将使用 strptime 初始化我的结果 tm 结构,如果转换为 returnCode 出现问题,甚至会返回。有谁知道如何做到这一点?我可以以某种方式定义带有两个参数的访问者......或者其他什么?