Search code examples
c++boost-any

Why doesn't boost::any have a "getter"?


Using boost::any is very useful but it's very depressing that it has no getter, and always we have to use any_cast for casting it to type we want. But why it has no such thing? In my opinion the one bellow can be useful member. Is there some bad things I can't see?

template <class T>
void get(T * handle)
{
    *handle = boost::any_cast<T>(*this);
}

Edit:

The only bad thing I see, that this getter requires to have assignment operator.


Solution

  • Probably because it'd behave the exact same as any_cast, but it would be less descriptive. any_cast indicates that you're performing a cast, a type conversion. You're trying to get the value out of the any object. So it's clear to the user that the operation can fail if you call it with the wrong type.

    A get function is less clear about failure conditions. I normally wouldn't expect that a function simply named get is able to fail. And if it does, I'm not sure of the semantics of it.

    If you want a get function, perhaps you should use boost::variant instead.