在C++的另一个类中使用模板类

Use template class in another class in C++

本文关键字:另一个 C++      更新时间:2023-10-16

我有一个模板类,我想在另一个类中使用。问题是我想在不知道实际类型的情况下使用模板类。

一个简单的例子:

template <class T> 
class Foo{
    private:
        T x_;
    public:
        void Foo(T);
};

现在,另一个使用Foo的类。我想做的是:

class Bar{
    private:
        Foo foo_;
    public:
        Bar(Foo);
};

问题是FooBar 中使用时需要一个模板参数。如果 Bar 类可以使用任何模板参数处理Foo,那就太好了。有解决方法吗?

使Bar本身成为类模板

template <typename T>
class Bar{
    private:
        Foo<T> foo_;
    public:
        Bar(Foo<T>);
};

或者,您可以在通用多态界面下键入擦除Foo。这限制了Foo的使用,并引入了运行时和内存开销。

struct FooBase {
    virtual ~FooBase() { }
    virtual void Xyz(int) { }  
};
template <class T> 
class Foo : FooBase {
    private:
        T x_;
    public:
        void Foo(T); 
        void Xyz(int) override 
        {
            // `T` can be used in the definition, but 
            // cannot appear in the signature of `Xyz`.
        }
};
class Bar{
    private:
        std::unique_ptr<FooBase> foo_;
    public:
        Bar(std::unique_ptr<FooBase>&&);
};
相关文章: