在 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
.然后我可以存储不同的类型 int
和 int const
(准确地说是指向 foo<int>
和 foo<int const>
类型对象的指针)在 bar*
的 vector 中秒。然后对于给定的类型(此处为 int const
),我检查此 vector 中的每个元素是否可以动态转换为 foo
。用这种类型。
运行此代码时 t3
变成 nullptr
和 t4
一个非空指针。但我想要 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/