将模板信息保存在子类中

Saving template information in Subclass

本文关键字:存在 子类 保存 信息      更新时间:2023-10-16

我有一个带有函数的父类。在这个函数中,我想调用一个模板方法,但模板的类型取决于子类的类型。所以我想在那里保存有关 T 的信息。我不能用模板调用foo,因为它来自程序的另一部分,我无法更改

class A
{
    //this will be called on an instance of B or C, A will never be 
    //instantiated
    void foo()
    {
        ba<T>();
    }
}

class B :public A
{
//T want to save here the Type of T so i won't have to call foo() with 
//a template
}
class C :public A
{
//here comes another Type for T
}
你需要

的是一个CRTP模式,这在C++模板编程中很常见。

template<class T>
void ba() {}
template<class Derived>
struct A
{
    void foo() {
        ba<typename Derived::MyT>();
    }
};
struct B
    : public A<B>
{
    using MyT = int;
};
struct C
    : public A<C>
{
    using MyT = double;
};

int main() {
    B b;
    b.foo();
    C c;
    c.foo();  
}

您需要将模板参数添加到基类 A,然后在 B 和 C 的声明中指定类型。 请参阅以下示例:

template <typename T>
class A
{
    public:
    void foo()
    {
        ba<T>();
    }
};

class B : public A<int>
{
};
class C : public A<bool>
{
};
int main()
{
    B b;
    C c;
    b.foo(); // This calls ba<int>()
    c.foo(); // This calls ba<bool>()
    return 0;
}

花一些时间查看模板和继承的工作原理可能会很好。

遗产

模板