Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::any typeid optimization for C++11 [duplicate]

Tags:

c++

c++11

stl

boost

Possible Duplicate:
When can typeid return different type_info instances for same type?

If I change the operand->type() == typeid(ValueType) line below into &operand->type() == &typeid(ValueType), the code still works with gcc and takes up less space in the executable (and did so for many years now), but does the C++11 standard give any guarantees, that this optimization should work across different compilers?

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;
}
like image 996
user1095108 Avatar asked Apr 12 '12 06:04

user1095108


1 Answers

No, it's not guaranteed. This assert may trigger:

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

While it would take a pretty stupid compiler to make that fire, it could happen. In practice, it will only fail when typeid's are being compared across dynamic library boundaries:

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

This will almost certainly trigger.

like image 197
GManNickG Avatar answered Sep 29 '22 07:09

GManNickG