c++ - 如何在 C++ 运行时确定数据类型?

标签 c++ type-conversion

我有一个派生自 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/

相关文章:

c++ - 内部类和外部成员的访问

C++: "T a = b"-- 复制构造函数还是赋值运算符?

c++ - 如何使用typeid检查您的对象是哪个派生类?

无需访问库即可将整数转换为字符串

c++ - C/C++ : Conversion of char[] to int fails, unsigned char[] to int 有效,为什么?

c++ - 为什么这个案例 block 不执行?

c++ - 等价和平等有什么区别?

r - 当日期格式无法识别时,如何减去 R 中的日期列?

c# - 如何在 Entity Framework 中使用 Date Only 作为数据类型

c++ - 你如何散列一个字符串?我需要以某种方式将随机字符串转换为整数以将它们放入我的哈希表中