使用类型擦除创建运行时type_traits查询
Using Type-Erasure to create runtime type_traits queries
是否可以
使用类型擦除来创建封装任意类型的对象(我们称之为ErasedType
),并且可以在运行时查询以判断另一个任意类型T
是否可以转换为ErasedType
?
经过思考,我认为这是不可能的——尽管理论上似乎有可能。 编译器会知道我们试图与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
的结果
那么,这可能吗?
一般来说,这在C++确实是不可能的。在运行时对类型进行任意查询需要相当多的元数据,C++试图保持最小值(有时有点烦人;一个功能可以自动选择加入"使用",所以没有不必要的开销,但我退出)。
正如 David 所暗示的那样,完全有可能在一定程度上复制编译器信息,但永远不会完全自动。这会将运行时类型信息限制为您手动添加的信息。
看看像Qt这样的库,它们在C++之上有一个完整的框架来提供这些元数据,看看涉及什么样的工作。根据手头的问题,您也许可以在没有它的情况下度过难关。
相关文章:
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 在 QVector<std::unique_ptr 上使用 std::find<Type>>
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 控制到达非空函数clang(-Wreturn-type)的末尾
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- 如何将 std::ifstream 转换为 std::basic_istream<CharT, Traits>&?
- 将系数存储在头文件的数组中("does not name a type"错误)
- 尝试打开 ifstream 时出现"Incomplete type"错误
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 在"结构提升::enable_if<提升::is_pod<T>,无效>"中没有名为"type"的类型
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- OpenCV CV_16F type
- C++ "错误:在'类 std::result_of< ... >"中没有名为'type'的类型"
- 将内存分配返回值强制转换为 TYPE 数组
- C++ 一个lambda浅拷贝const Type&如果它被赋予一个命名捕获,如[copy=val](){}?
- reference_wrapper导致"incomplete type is not allowed"
- 继承类时"invalid use of incomplete type ‘class tree_node_t’"
- 由于"error C4430: missing type specifier - int assumed. Note: C++ does not support default-int",我现在无法编
- cv::D ataType<> 与 cv::traits::Type<>