Cha*_*l72 5 c++ templates type-erasure
是否可以使用Type Erasure创建封装任意类型的对象(让我们称之为ErasedType),并且可以在运行时查询以判断另一个任意类型是否T可以转换为ErasedType?
考虑这件事后,我不认为这是可能的-尽管现在看来,这可能潜在有可能在理论上.编译器会知道T我们要与哪些类型进行比较ErasedType,因此可以在运行时生成必要的代码.问题是,在实践中,似乎没有任何方法可以将模板参数类型从Base类实例传递给Subclass实例.
例如:
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
}
};
Run Code Online (Sandbox Code Playgroud)
所以,目标是能够说出类似的话:
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
Run Code Online (Sandbox Code Playgroud)
但是,我看不出该FooBase::is_convertible方法是如何实现的,因为我看不到在同一个函数中一起制作TestType和ErasedType访问,所以编译器可以计算结果std::is_convertible<TestType, ErasedType>::value
那么,这有可能吗?