我有一个派生自 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 库,据我所知,它确实支持类型。
更新:
正如问题下的评论提到的 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)
}
只是不要忘记在类里面交这个“ friend ”。
关于c++ - 如何在 C++ 运行时确定数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36407169/