隐藏多态细节,用户看到的只是一个concrete class,思想来自于Better Code: Runtime Polymorphism - Sean Parent
以下代码直到gcc 9.2编译会通过,但是运行会出现段错误,在model
的构造函数列表中data_{std::move(t)}
会被gcc解释成构造列表,此行为似乎与标准相悖,必须改成data_(std::move(t))
,强制gcc使用拷贝构造函数才行。clang无此问题
#include <algorithm>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <future>
#include <chrono>
template <typename T>
void draw(const T &x, std::ostream &out, std::size_t pos) {
out << std::string(pos, ' ') << x << std::endl;
}
class object_t final {
public:
template <typename T> object_t(T x) : self_(std::make_shared<model<T>>(std::move(x))) {
}
friend void draw(const object_t &t, std::ostream &out, std::size_t pos) {
t.self_->draw_(out, pos);
}
private:
struct concept_t {
virtual ~concept_t() = default;
virtual void draw_(std::ostream &out, std::size_t pos) const = 0;
};
template <typename T