gpt4 book ai didi

c++ - 使用类型删除创建运行时 type_traits 查询

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:16 25 4
gpt4 key购买 nike

是否有可能使用类型删除来创建封装任意类型的对象(我们称之为 ErasedType ),并且可以在运行时查询以判断是否存在另一个任意类型 T可转换为 ErasedType

考虑之后,我不认为这是可能的 - 尽管看起来它在理论上可能是可能的。编译器会知道哪些类型 T我们正在尝试与 ErasedType 进行比较,因此可以在运行前生成必要的代码。问题是,在实践中,似乎没有任何方法可以将模板参数类型从基类实例传递到子类实例。

例如:

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方法可以实现,因为我看不出有什么办法可以制作TestTypeErasedType在同一个函数中一起访问,因此编译器可以计算 std::is_convertible<TestType, ErasedType>::value 的结果

那么,这有可能吗?

最佳答案

在C++中确实是不可能的,一般。在运行时对类型进行任意查询需要相当多的元数据,而 C++ 试图将这种情况保持在最低限度(有时会有点烦人;一个功能可以自动选择“使用”,所以没有不必要的开销,但我离题了)。

正如 David 一直在暗示的那样,完全有可能将编译器信息复制到一定程度,但绝不会完全自动。这将运行时类型信息限制为您手动添加的内容。

看看像 Qt 这样的库在 C++ 之上有一个完整的框架来提供元数据以查看涉及的工作类型。根据手头的问题,您可以不用它。

关于c++ - 使用类型删除创建运行时 type_traits 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11905674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com