/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include #include #include #include #include #include "common/enforce.h" #include "common/log.h" #include "common/type_define.h" namespace paddle_mobile { template struct IDToType { typedef Type type_t; }; template struct VariantHelper { inline static void Destroy(kTypeId_t type, void *raw_ptr) { if (type == type_id()) { auto ptr = reinterpret_cast(raw_ptr); delete ptr; } else { VariantHelper::Destroy(type, raw_ptr); } } }; template struct VariantHelper { inline static void Destroy(kTypeId_t type, void *raw_ptr) { if (type == type_id()) { auto ptr = reinterpret_cast(raw_ptr); delete ptr; } } }; template struct VariantDeleter { kTypeId_t type_ = type_id().hash_code(); explicit VariantDeleter(kTypeId_t type) { type_ = type; } void operator()(void *raw_ptr) { // DLOG << "variant delete: " << type_ << " " << raw_ptr; VariantHelper::Destroy(type_, raw_ptr); } }; template struct Variant { Variant() : type_(invalid_type()) {} Variant(const Variant &variant) { type_ = variant.type_; data_ = variant.data_; } virtual ~Variant() { // DLOG << "variant deinit: " << type_ << " " << (void *)data_.get(); data_.reset(); } template void Set(Args &&... args) { auto raw_ptr = new T(std::forward(args)...); type_ = type_id().hash_code(); // DLOG << "variant new: " << type_ << " " << (void *)raw_ptr; data_.reset(raw_ptr, VariantDeleter(type_)); } template T &Get() const { return *const_cast(reinterpret_cast(data_.get())); } kTypeId_t TypeId() const { return type_; } private: static inline kTypeId_t invalid_type() { return type_id().hash_code(); } typedef VariantHelper helper; kTypeId_t type_ = type_id().hash_code(); std::shared_ptr data_; }; template struct Vistor { typedef T type_t; }; } // namespace paddle_mobile