beg*_*neR 1 c++ templates class
我有一个模板类,我想在另一个类中使用.问题是我想在不知道实际类型的情况下使用模板类.
一个简单的例子:
template <class T>
class Foo{
private:
T x_;
public:
void Foo(T);
};
Run Code Online (Sandbox Code Playgroud)
现在,另一个类使用Foo.我想做的是:
class Bar{
private:
Foo foo_;
public:
Bar(Foo);
};
Run Code Online (Sandbox Code Playgroud)
问题是Foo在内部使用时需要模板参数Bar.如果Bar类可以处理Foo任何模板参数,那将是很好的.有解决方法吗?
使Bar自己成为一个类模板:
template <typename T>
class Bar{
private:
Foo<T> foo_;
public:
Bar(Foo<T>);
};
Run Code Online (Sandbox Code Playgroud)
或者,您可以在常见的多态接口下键入擦除 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>&&);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1987 次 |
| 最近记录: |