0

假设我有一个

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 出现问题,甚至会返回。有谁知道如何做到这一点?我可以以某种方式定义带有两个参数的访问者......或者其他什么?

4

2 回答 2

1

您简单的示例调用应该可以工作。向接受引用并存储它的访问者添加一个构造函数,例如:

 tm* target;
 timeVisitor( tm& a ) : target(&a) {}
 int operator()(string &str) const {
      strptime(str.c_str(), "%Y-%m-%d", target);
 }
于 2011-10-27T12:35:24.760 回答
1

事实上,完全允许在创作时给访问者一个论据。您在问题末尾编写的代码是这样做的好方法:

tm result;
int returnCode = boost::apply_visitor( timeVisitor(result), myVariant );

这是访问者的外观:(未经我测试,可能有轻微的语法错误)

class timeVisitor : public boost::static_visitor<bool>
{
public:
    timeVisitor(tm& s):m_tm(s) {}

    bool operator()(string &str) const
    {
        return strptime(str.c_str(), "%Y-%m-%d", m_tm.get());
        // in case of error, NULL pointer is converted to false automatically
    }
protected:
    tm& m_tm;
};
于 2011-10-27T13:04:16.987 回答