1

我正在测试以下代码:

typedef boost::variant<int, std::string> Type;
typedef boost::variant<std::vector<int>, std::vector<std::string> > Container;

class Setter: public boost::static_visitor<>
{
public:
    Setter(Container& container): _container(container) 
    {
    }

    template <class T>
    void operator()(const T& valueToSet) 
    {
        std::vector<T> *container = boost::get< std::vector<T> >(&_container);
        if(container->size()==0)
        {
            container->resize(1);
        }
        (*container)[0] = valueToSet;
    }

private:
    Container& _container;
};

使用以下单元测试:

TEST_F (TestSet, addIncorrectTypeToContainer)
{
    Container container((std::vector<std::string>()));
    Setter setter = Setter(container);
    ASSERT_THROW(boost::apply_visitor(setter, Type(int(1))), boost::bad_get);
}

我没有得到 boost::bad_get 异常。相反,它返回 NULL。

我究竟做错了什么?

4

1 回答 1

2

这是答案:

返回指向保持值的引用/指针:

If a pointer is passed: Returns a pointer to the held value if its type is ToType. Otherwise, returns NULL.
If a value/reference is passed: Returns a reference to the held value if its type is ToType. Otherwise, throws a bad_get exception.
于 2012-10-10T15:58:39.007 回答