为什么 boost::any 没有“吸气剂”?

发布于 2024-11-04 11:23:14 字数 345 浏览 6 评论 0原文

使用 boost::any 非常有用,但令人沮丧的是它没有 getter,而且我们总是必须使用 any_cast 将其转换为我们想要的类型。但为什么没有这样的东西呢?在我看来,下面的一位可能是有用的成员。是不是有什么不好的事情我看不见?

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

编辑:

我看到的唯一不好的事情是,这个 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

歌枕肩 2024-11-11 11:23:14

可能是因为它的行为与 any_cast 完全相同,但描述性较差。 any_cast 表示您正在执行强制转换(类型转换)。您正在尝试any对象中获取值。因此,用户很清楚,如果使用错误的类型调用操作,操作可能会失败。

get 函数对于失败条件不太清楚。我通常不会期望一个简单地名为 get 的函数能够失败。如果确实如此,我不确定它的语义。

如果您想要一个 get 函数,也许您应该使用 boost::variant 来代替。

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.

够钟 2024-11-11 11:23:14

any_cast 的要点是强制人们使用模板参数推导,因为转换的失败与否对于精确非常敏感用于构造的类型。

这种用法很清楚:

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

这不是:

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

Now替换

int g;

事实上,想象一下现在你重构你的代码,然后用

double g;

,新代码看起来像这样

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

这可能会让你损失一些半小时的调试时间。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文