Baz
Baz

Reputation: 13135

Not getting boost::bad_get exception for boost::get

I have the following code which I'm tesing:

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;
};

with the following unit test:

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);
}

I'm not getting the boost::bad_get exception. Instead its returning NULL.

What am I doing wrong?

Upvotes: 1

Views: 3087

Answers (1)

Baz
Baz

Reputation: 13135

Here's the answer:

Returns a reference/pointer to a held value:

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.

Upvotes: 2

Related Questions