Reputation: 1329
I have a class B which derives from A:
template<class T>
class A
{
class iterator; // Defined fully
iterator begin ()
{
// Returns a pointer to the first element
}
iterator end ()
{
// Returns a pointer to the last element
}
}
template <class T>
class B : public A
{
// It automatically inherits the iterator
}
template <typename InputIterator>
void foo (InputIterator first,InputIterator last)
{
// Some code to infer whether it is of type A or B
}
Now some function say foo()
is called using B::begin()
at one time and sometime with A::begin()
.
I need to determine type during runtime to infer type and set some flag variables. How do I do this? I tried using typeinfo()
but it returns the same value for both the iterators.
Upvotes: 0
Views: 129
Reputation: 860
typeinfo()
returns the same value, because both A::begin()
and B::begin()
give you a value of the same type.
You should either have B::iterator
inherit from A::iterator
or have a special function in your iterator that returns a reference/pointer to it's container (which is then either of type A
or type B
).
Upvotes: 0
Reputation: 46
From library type_traits you can use some type magic:
is_base_of - returns true if Base is base of Derived.
is_same - returns true if A is the same type as B.
Everything with type_traits can be found here http://www.cplusplus.com/reference/type_traits/?kw=type_traits
They are not so runtime, it's only some magic with structs and templates, C++ does not support type as data by default. If you want so you can use Boost library, it does support types as I know.
UPD:
As comments under the question mentioned A::iterator is absolutely the same with B::iterator, so without looking at classes they are the same memory chunk.
So solution (maybe) is to create a little different function, what depends on classes actually:
template <typename LeftClass, typename RightClass>
void foo (LeftClass left, RightClass right)
{
if(is_same<LeftClass, RightClass>::value)
{
}
//Or that
if(is_same<LeftClass, A>::value && is_same<RightClass, A>::value)
}
Just don't forget to make this "friend" with classes.
Upvotes: 1