我有一个从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
}
现在,某些函数说
foo()
是一次使用B::begin()
调用的,有时是使用A::begin()
调用的。我需要在运行时确定类型以推断类型并设置一些标志变量。我该怎么做呢?我尝试使用
typeinfo()
,但是对于两个迭代器,它返回相同的值。 最佳答案
在库type_traits中,您可以使用一些类型魔术:
is_base_of-如果Base是Derived的底数,则返回true。
is_same-如果A与B的类型相同,则返回true。
带有type_traits的所有内容都可以在这里找到http://www.cplusplus.com/reference/type_traits/?kw=type_traits
它们不是运行时,而是结构和模板的魔力,C ++默认不支持将类型作为数据。如果愿意,可以使用Boost库,它确实支持我所知道的类型。
UPD:
正如在该问题下提到的注释一样,A :: iterator与B :: iterator完全相同,因此,不查看类,它们是相同的内存块。
因此,解决方案(也许)是创建一个稍微不同的函数,实际上取决于类:
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)
}
只是别忘了与班上的这个“朋友”。
关于c++ - 如何在C++中的运行时确定数据类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36407169/