// // Created by zwsd // #pragma once #include #include #include #include #include #include #include #include #include #include #include #include /** * @brief * * service: ServiceContrainer * * 监听事件: * 依赖状态: * 依赖服务: * 作用: * */ // std::shared_ptr buf(new Buffer()); // Any any(buf); // std::shared_ptr b = any.Get>(); // assert(buf.get() == b.get()); namespace iflytop { namespace core { using namespace std; class Any { public: Any() : content_(nullptr) {} ~Any() { delete content_; } template explicit Any(const ValueType& value) : content_(new AnyHolder(value)) {} Any(const Any& other) : content_(other.content_ ? other.content_->clone() : nullptr) {} public: Any& swap(Any& rhs) { std::swap(content_, rhs.content_); return *this; } template Any& operator=(const ValueType& rhs) { Any(rhs).swap(*this); return *this; } Any& operator=(const Any& rhs) { Any(rhs).swap(*this); return *this; } bool IsEmpty() const { return !content_; } const std::type_info& GetType() const { return content_ ? content_->GetType() : typeid(void); } template ValueType operator()() const { return Get(); } template ValueType Get() const { if (GetType() == typeid(ValueType)) { return static_cast*>(content_)->held_; } else { return ValueType(); } } protected: class AnyPlaceHolder { public: virtual ~AnyPlaceHolder() {} public: virtual const std::type_info& GetType() const = 0; virtual AnyPlaceHolder* clone() const = 0; }; template class AnyHolder : public AnyPlaceHolder { public: AnyHolder(const ValueType& value) : held_(value) {} virtual const std::type_info& GetType() const { return typeid(ValueType); } virtual AnyPlaceHolder* clone() const { return new AnyHolder(held_); } ValueType held_; }; protected: AnyPlaceHolder* content_; template friend ValueType* any_cast(Any*); }; template ValueType* any_cast(Any* any) { if (any && any->GetType() == typeid(ValueType)) { return &(static_cast*>(any->content_)->held_); } return nullptr; } template const ValueType* any_cast(const Any* any) { return any_cast(const_cast(any)); } template ValueType any_cast(const Any& any) { const ValueType* result = any_cast(&any); assert(result); if (!result) { return ValueType(); } return *result; } } // namespace core } // namespace iflytop