c++ - 在 C++ 中检查运行时的可转换性

标签 c++ type-conversion

在 C++ 中,不同的类型转换是隐式完成的。例如 int 类型的对象可以分配给const int (如以下代码中主函数的第一行所做的那样)。

现在我想在运行时检查可转换性,因为我有一个可以添加类型的结构,稍后我想检查给定类型是否存储在结构中的类型之一可以转换为给定类型类型。

这是我到目前为止的想法:

#include <iostream>
#include <vector>

struct bar { virtual void dummy() {} };
template<typename T> struct foo : public bar { virtual void dummy() {} };

int main() {

    int i1 = 1;
    const int i2 = i1;

    std::vector<bar*> bars;
    bar* t1 = new foo<int>; bars.push_back(t1);
    bar* t2 = new foo<int const>; bars.push_back(t2);

    foo<int const>* t3 = dynamic_cast<foo<int const>*>(bars[0]);
    std::cout << t3 << std::endl;

    foo<int const>* t4 = dynamic_cast<foo<int const>*>(bars[1]);
    std::cout << t4 << std::endl;

    delete t1;
    delete t2;

    return 0;
}

为了在结构中存储类型,我创建了模板化结构 foo源自 bar .然后我可以存储不同的类型 intint const (准确地说是指向 foo<int>foo<int const> 类型对象的指针)在 bar* 的 vector 中秒。然后对于给定的类型(此处为 int const ),我检查此 vector 中的每个元素是否可以动态转换为 foo。用这种类型。

运行此代码时 t3变成 nullptrt4一个非空指针。但我想要 t3也是一个非空指针。

我希望我想做什么已经大致清楚了。

您是否有任何想法如何在运行时实现这种可转换性检查(涉及 c++11 功能的解决方案完全没问题)?

最佳答案

不幸的是,自foo<int>foo<const int>是完全不相关的类型,你不能轻易做到这一点。

bar* t1 = new foo<int>;
foo<int const>* t3 = ?????<foo<int const>*>(t1);

t3不能是 t1 任何部分的指针, 自 t1既不是也不包含 foo<int const>对于 t3指向。从中获得任何良好行为的唯一方法是制作一个拷贝 t1 的数据。持有一个全新的foo<int const>* .这种令人沮丧的限制是模板可专门化为不相关类型的副作用,这是一个非常强大的工具,但会导致这种困惑。一般的经验法则是不要将 const/volatile 限定条件或任何类型的引用放入模板参数中,除非这是模板类的唯一原因(例如 std::remove_reference )。

但是,我才意识到,你想要的是 foo<int>foo<const int>是同一类型(ish),可以完成(sortof)!

struct base { 
    virtual ~base(){}; //always have virtual destructor with polymorphism
    virtual void dummy()=0; //pure virtual, forces override
};
template<typename T> 
struct foo : public bar { 
    virtual void dummy() {} 
};
template<typename T> struct foo<const T> : public foo<T> {};
template<typename T> struct foo<volatile T> : public foo<T> {};
template<typename T> struct foo<const volatile T> : public foo<T> {};


base* t1 = new derived<const int>;
derived<int>* t3 = dynamic_cast<derived<int>*>(t1); //hooray!
//you can go from derived<const int> to derived<int> but not the other way around

关于c++ - 在 C++ 中检查运行时的可转换性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17372863/

相关文章:

android - 如何将 Picture 对象转换为 Bitmap 对象,Android

pdf - Word Automation Service 断开目录中的链接

c++ - 如何处理 Bazel 中的 C++ 库循环依赖?

声明中的 C++ 引用运算符

c++ - 透视矩阵的旋转角度

c++ - 运行期间传递的参数的平方根

c++ - 开发 H264 硬件解码器 Android - Stagefright 或 OpenMax IL?

c++ - 交接功能作为有参数的参数

c# - 获取 SPFieldCurrency 字段的数值

c# - 如何在 C# 中将 ArrayList 转换为字符串数组(string[])