[英]How can I determine data type during runtime in C++?
I have a class B which derives from A: 我有一个从A派生的B类:
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()
. 现在,有些函数说
foo()
是一次使用B::begin()
调用的,而有时是通过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. 我尝试使用
typeinfo()
但它为两个迭代器返回相同的值。
From library type_traits you can use some type magic: 在库type_traits中,您可以使用一些类型魔术:
is_base_of - returns true if Base is base of Derived. is_base_of-如果Base是Derived的底数,则返回true。
is_same - returns true if A is the same type as B. is_same-如果A与B的类型相同,则返回true。
Everything with type_traits can be found here http://www.cplusplus.com/reference/type_traits/?kw=type_traits 带有type_traits的所有内容都可以在这里找到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. 它们不是运行时,而是结构和模板的魔力,C ++默认不支持将类型作为数据。 If you want so you can use Boost library, it does support types as I know.
如果愿意,可以使用Boost库,它确实支持我所知道的类型。
UPD: 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. 正如在该问题下提到的注释一样,A :: iterator与B :: iterator完全相同,因此,不查看类,它们是相同的内存块。
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. 只是别忘了与班上的这个“朋友”。
typeinfo()
returns the same value, because both A::begin()
and B::begin()
give you a value of the same type . typeinfo()
返回相同的值,因为A::begin()
和B::begin()
为您提供了相同类型的值。
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
). 您应该让
B::iterator
从A::iterator
B::iterator
继承,或者在A::iterator
有一个特殊的函数,该函数将对其容器的引用/指针返回(然后是类型A
或类型B
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.