gpt4 book ai didi

c++ - 将专门的基指针转换为专门针对附加模板参数 ("adding on"专门化的派生指针)

转载 作者:行者123 更新时间:2023-11-28 06:41:46 24 4
gpt4 key购买 nike

我想将基类指针转换为派生类指针,以便利用派生类独有的一些方法。这是一个 Ideone一个有效的简单示例:

template<typename A>
class Base {};

template<typename A, typename B>
class Derived : public Base<A> {
public:
void doSomething() {}
};

int main() {
Base<int>* foo = new Derived<int, double>;
static_cast<Derived<int, double>*>(foo)->doSomething();
return 0;
}

现在,问题是我的 foo 实际上是模板类的成员,

template<typename A>
class Container
{
public:
Base<A>* foo;
};

在我转换的时候,我不知道A是什么:

int main() {
Container<int> container;
container.foo = new Derived<int, double>;

// a lot of code later...
static_cast<Derived< /* ??? */ , double>*>(container.foo)->doSomething();

return 0;
}

然后我想如果我能以某种方式将 A 存储在我的基类中,这可能是可能的,比如

template<typename A>
class Base
{
public:
static type template_type = A; // made-up syntax
};

这样我就可以引用它了

static_cast<Derived<container.template_type, double>*>(container.foo)->doSomething();

但根据this question在 C++ 中存储类型是不可能的。

如何在不知道 A 的情况下实现此转换?

也就是说,我如何将专用基指针转换为专门用于附加模板参数的派生指针?用不太专业的术语来说,我只想采用一个 Base 指针并添加形成 Derived 指针所需的其他特化。

最佳答案

通常做向上转换是不明智的,通常有更好的设计可以用来避免向上转换的需要,但如果你真的需要它,那么你可以使用 dynamic_cast做这个。

此运算符尝试动态地从一种类型转换为另一种类型,如果无法转换,它将返回 nullptr。但请记住,它只适用于多态类型(至少有一个 virtual 函数的类型)所以在这种情况下你的 Base 类必须是多态的(因为你持有一个指针对于基类,您可能需要一个虚拟析构函数来允许 delete 处理基指针,这使得 Base 成为一个多态类。

但要记住 C++ 中的类型,您有 2 个选择:

  • 使用typedef:

您可以使用 typedef 来保存类中的类型信息:

template< class A >
class my_class
{
public:
typedef A input_type;
};

template< class T >
void do_something(T const& t)
{
typename T::input_type n;
do_something_on_input_type(n); // possibly overloaded for different input types
}

这种方法非常快并且在运行时没有开销,但您只能在需要在编译时执行某些操作的情况下使用它。如果直到运行时才确定指针的类型,则此方法没有用。

使用这个你实际上可以保存类的类型信息:

class Base { virtual std::type_info const& get_type() const = 0; };
class Child : public Base
{
virtual std::type_info const& get_type() const { return typeid(Child);
void child_specific_function() { /**/ }
}
class ChildOfChild : public Child
{
virtual std::type_info const& get_type() const { return typeid(ChildOfChild); }
// ...
};

void do_something(Base* base)
{
if (base->get_type() == typeid(Child))
{
static_cast<Child*>(base)->child_specific_function();
}
}

这听起来很有趣,但是,它只有在您知道对象的确切类型时才有用,它不适用于派生类型,因此这种方法适用于 Child 但不适用于 ChildOfChild

关于c++ - 将专门的基指针转换为专门针对附加模板参数 ("adding on"专门化的派生指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25836394/

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