【问题标题】:boost::any typeid optimization for C++11 [duplicate]boost::any typeid 优化 C++11 [重复]
【发布时间】:2012-04-12 06:33:40
【问题描述】:

可能重复:
When can typeid return different type_info instances for same type?

如果我将下面的operand->type() == typeid(ValueType) 行更改为&operand->type() == &typeid(ValueType),代码仍然可以使用 gcc,并且在可执行文件中占用更少的空间(并且已经这样做了很多年),但是 C++11 标准是否给出了任何保证,这种优化应该适用于不同的编译器?

template<typename ValueType>
ValueType * any_cast(any * operand)
{
    return operand && 
#ifdef BOOST_AUX_ANY_TYPE_ID_NAME
        std::strcmp(operand->type().name(), typeid(ValueType).name()) == 0
#else
        operand->type() == typeid(ValueType)
#endif
        ? &static_cast<any::holder<ValueType> *>(operand->content)->held
        : 0;
}

【问题讨论】:

  • 从技术上讲,这是一个 C++03 问题,而这个问题是 C++11。编辑使其明确不重复(答案仍然正确)

标签: c++ boost stl c++11


【解决方案1】:

不,不能保证。这个断言可能会触发:

assert(&typeid(int) == &typeid(int));

虽然需要一个非常愚蠢的编译器才能引发火灾,但它可能会发生。实际上,只有在跨动态库边界比较 typeid 时才会失败:

assert(&typeid_of_int_in_lib1() == &typeid_of_int_in_lib2());

这几乎肯定会触发。

【讨论】:

  • 找到这篇文章,断言可能会在 Windows 中触发,但在 linux 中可能不会:link
  • @user1095108:啊,毕竟是重复的。 :)
  • 不完全是,如果他们静态链接,人们可能仍然会破解他们的 any.hpp。
  • 只有在编译时隐藏可见性的类才会在 linux 中失败。
猜你喜欢
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多