On Wednesday, 23 December 2015 02:33:50 UTC+2, Alf P. Steinbach wrote:
> On 12/22/2015 7:33 PM, Richard wrote:
> > [Please do not mail me a copy of your followup]
> >
> >
porp...@gmail.com spake the secret code
> > <
e16c168f-ff72-4a9b...@googlegroups.com> thusly:
> >
> >> Is the following typeid comparison correct in all cases ?
> >> typeid(T1) == typeid(T2);
> >
> > An alternative is to use std::is_same<T1, T2>::value.
> > <
http://en.cppreference.com/w/cpp/types/is_same>
>
> Your alternative std::is_same more likely to be the practical choice.
> For with a few exceptions, checking the identity of two types only makes
> sense in template code, and there it's ungood to have the result only at
> run-time. std::is_same provides a compile time result.
On most cases when I have seen 'typeid' result compared it was design
defect or code smell ... like missing virtual function or missing visitor
pattern. For some people visitor pattern is hard to grasp but I have never
observed typeid-comparing code being easier to maintain for such people.
However sometimes 'typeid' is a good choice, particularly when involved
types may be polymorphic pointers from different inheritance trees or
when 'name' is also needed for something (say code generation).
>
> In the cases where one really does want to compare std::type_info
> instances, using std::type_index is usually preferable, because
> std::type_info lacks a "operator<" named as such.
>
> With a pre-C++11 compiler a class like std::type_index can be easily
> defined, and indeed Andre Alexandrescu defined one in his classic book
> "Modern C++ Design" (still worth reading, I think).
You are correct that 'std::type_index' is simpler to use. Lack of 'operator<'
can be compensated with 'std::type_info::before'. Bigger problem is that
'std::type_info' is not copyable and so can't be stored. 'std::type_index'
deals with it more safely (and sometimes more efficiently) than raw
pointers to 'std::type_info'.
Merry Christmas