开发者

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. Bu开发者_开发知识库t 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.


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.


The point with any_cast is to force people not to use template argument deduction, since the failure or not of the cast is very sensitive to the exact type used for construction.

This usage is clear:

any x(2); // store an int
double f = any_cast<int>(x); // ok, request for an int, then cast to double

This one is not:

int g;
...
x.get(&g); // Ok. For now.

Indeed, imagine now you refactor your code, and you replace

int g;

by

double g;

Now, the new code looks like

double g;
... // There can be 100s of lines here
x.get(&g); // This line HAS changed semantics and cast will fail

This will likely make you lose some half hours to debug.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜