作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 C++ 14、模板和桥接模式,我正在尝试创建一种通用方法,将对象添加到名为 Shapes(Shape 对象的 vector )的容器中。我希望能够自动支持添加到容器中的新数据类型并在不修改 Shape 类的原始实现的情况下打印它们。相反,我只想提供一个新的 print(T) 函数,一切都应该开箱即用。
下面是我的代码,我在编译它时仍然遇到了一些问题。谁能帮帮我?非常感谢。
#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <string>
using namespace std;
void print(const int toPrint) {
cout << " " << toPrint;
cout << endl;
}
void print(const double toPrint) {
cout << " " << toPrint;
cout << endl;
}
void print(const vector<int> & toPrint) {
for (auto & it : toPrint) {
cout << " " << it;
}
cout << endl;
}
void print(const map<int, string> & toPrint) {
for (auto & it : toPrint) {
cout << " " << it.first << " : " << it.second << endl;
}
cout << endl;
}
class Shape {
public:
template<typename T>
Shape(T &&t) {
pimpl_ = make_unique<Specialization<T>>(t);
}
void print() const {
pimpl_->print();
}
private:
struct Base {
virtual void print() const = 0;
virtual ~Base() = default;
};
template<typename T>
struct Specialization: public Base {
Specialization(T &t) :
internalObject_ { std::move(t) } {
}
void print() const override {
::print(internalObject_);
}
T internalObject_;
};
unique_ptr<Base> pimpl_;
};
typedef vector<Shape> Shapes;
void print(Shapes const & shapes) {
for (auto & shape : shapes) {
shape.print();
}
}
int main() {
Shapes shapes;
shapes.push_back(1);
shapes.push_back(2.0);
shapes.push_back(0.3);
shapes.push_back(vector<int> { 10, 11, 12 });
shapes.push_back(map<int, string> { { 0, "elmo" }, { 1, "leom" } });
print(shapes);
return 0;
}
最佳答案
这里是你的代码的一个补丁版本,它可以编译(在 clang 上)。正如评论中指出的那样,有几个问题需要解决(例如,这段代码会泄漏内存),但这应该能让您回到正轨。
#include <iostream>
#include <vector>
using namespace std;
void print(int toPrint) {
cout << " " << toPrint;
cout << endl;
}
void print(double toPrint) {
cout << " " << toPrint;
cout << endl;
}
void print(vector<int> toPrint) {
for (auto & it : toPrint) {
cout << " " << it;
}
cout << endl;
}
class Shape {
public:
template<typename T>
Shape(T t) {
pimpl_ = new Specialization<T>(t);
}
void print() const{
pimpl_->print();
}
private:
struct Base {
virtual void print() const = 0;
};
template<typename T>
struct Specialization: public Base {
Specialization(T t) {
internalObject_ = new T(t);
}
void print() const{
::print(*internalObject_);
}
T* internalObject_;
};
Base * pimpl_;
};
typedef vector<Shape> Shapes;
void print(Shapes const & shapes) {
for (auto & shape : shapes) {
shape.print();
}
}
int main() {
Shapes shapes;
shapes.push_back(1);
shapes.push_back(2.0);
shapes.push_back(0.3);
shapes.push_back(vector<int> { 10, 11, 12 });
print(shapes);
return 0;
}
关于c++ - 泛型C++类的非侵入式设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43685548/
我是一名优秀的程序员,十分优秀!