我有一个B类,它来自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
}
现在有些函数说foo()
一次使用B::begin()
,有时使用A::begin()
调用。
我需要在运行时确定类型以推断类型并设置一些标志变量。我该怎么做呢?我尝试使用typeinfo()
,但它为两个迭代器返回相同的值。
答案 0 :(得分:1)
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.
答案 1 :(得分:0)
typeinfo()
返回相同的值,因为A::begin()
和B::begin()
都会为您提供相同类型的值 。
你应该让B::iterator
继承自A::iterator
,或者在你的迭代器中有一个特殊的函数,它返回一个引用它的容器的引用/指针(它的类型为{{1}或者输入A
)。