我有:
GeneralObject<Rectangle>
我应该如何实现此功能,以使Template类的向量具有任意形状?
我想一种方法是从3)中删除静态断言并创建类似以下内容的方法:
std::vector<GeneralObject <std::shared_ptr<Shape>>> objects;
但是我不确定我是否遵循正确的方法。如果我还可以断言模板函数使用Shape的子代,那就太好了。
将的成员更改GeneralObject
为T
而不是的指针T
:
template<typename T>
class GeneralObject {
public:
GeneraObject(std::shared_ptr<T> object) : object(object) {}
private:
std::shared_ptr<T> object;
};
您可以将其用作
auto gObj = GeneralObject<Shape>(std::make_shared<Rectangle>());
您的容器将是
std::vector<GeneralObject<Shape>> objects;
objects.emplace_back(std::make_shared<Rectangle>());
objects.emplace_back(std::make_shared<Circle>());
总而言之,像这样:
#include <iostream>
#include <memory>
#include <vector>
struct Shape {
virtual void draw() const = 0;
};
struct Rectangle : Shape {
void draw() const override { std::cout << "Rectangular drawing\n"; };
};
struct Circle : Shape {
void draw() const override { std::cout << "Circular drawing\n"; };
};
template <typename T>
class GeneralObject {
public:
GeneralObject(std::shared_ptr<T> object) : object(object) {}
void draw() const { object->draw(); }
private:
std::shared_ptr<T> object;
};
int main() {
std::vector<GeneralObject<Shape>> objects;
objects.emplace_back(std::make_shared<Rectangle>());
objects.emplace_back(std::make_shared<Circle>());
for (const auto& obj : objects) obj.draw();
}
这将输出
Rectangular drawing
Circular drawing
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句