gpt4 book ai didi

c++ - 泛型C++类的非侵入式设计

转载 作者:行者123 更新时间:2023-11-30 03:32:10 24 4
gpt4 key购买 nike

使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com