是否可以使用type来创建封装任意类型的对象(让我们称之为ErasedType),并且可以在运行时查询以判断另一个任意类型的T是否可以转换为ErasedType
经过思考,我认为这是不可能的--尽管理论上这似乎是可能的。编译器将知道我们试图与T进行比较的类型是什么,因此可以在运行时之前生成必要的代码。问题是,在实践中,似乎没有任何方法将模板参数类型从基类实例传递到子类实例。
例如:
struct FooBase
{
template <class TestType>
bool is_convertible()
{
return call_derived();
}
protected:
virtual bool call_derived() = 0;
template <class ErasedType>
void base_class_function() { }
};
template <class ErasedType>
struct Foo : public FooBase
{
bool call_derived()
{
// Here we have access to the ErasedType but no access to TestType.
//
// We could pass ErasedType to a base class function by saying:
//
// this->base_class_function<ErasedType>();
//
// ...but that doesn't seem to help since we still don't have access to
// TestType
}
};因此,我们的目标是能够说出这样的话:
FooBase* f = new Foo<int>();
bool res1 = f->is_convertible<double>(); // returns true
bool res2 = f->is_convertible<long>(); // returns true
bool res3 = f->is_convertible<std::string>(); // returns false但是,我看不出FooBase::is_convertible方法是如何实现的,因为我看不出如何使TestType和ErasedType在同一个函数中一起访问,所以编译器可以计算std::is_convertible<TestType, ErasedType>::value的结果
这有可能吗?
发布于 2012-08-10 19:06:03
一般来说,这在C++中是不可能的。在运行时对类型进行任意查询需要相当多的元数据,而C++试图将这种查询保持在最低限度(有时甚至有点烦人;一个特性可以自动被“使用”,所以没有不必要的开销,但我回避了)。
正如David所暗示的,在一定程度上完全有可能复制编译器的信息,但绝不会完全自动复制。这将运行时类型信息限制为手动添加的内容。
看一看像Qt这样的库,它在C++之上有一个完整的框架来提供这些元数据,以了解所涉及的工作类型。取决于手头的问题,你可能没有它就能度过难关。
https://stackoverflow.com/questions/11905674
复制相似问题