为什么 boost::any 没有“吸气剂”?
使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能是因为它的行为与
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 theany
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 namedget
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 useboost::variant
instead.any_cast
的要点是强制人们不使用模板参数推导,因为转换的失败与否对于精确非常敏感用于构造的类型。这种用法很清楚:
这不是:
Now替换
事实上,想象一下现在你重构你的代码,然后用
,新代码看起来像这样
这可能会让你损失一些半小时的调试时间。
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:
This one is not:
Indeed, imagine now you refactor your code, and you replace
by
Now, the new code looks like
This will likely make you lose some half hours to debug.