/* 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/variant.h" namespace paddle_mobile { namespace framework { using std::string; class Variable { public: template const T *Get() const { return static_cast(holder_->Ptr()); } template const T GetValue() const { return variant.Get(); } template void SetValue(T value) { variant.Set(value); } bool IsInitialized() const { return holder_ != nullptr; } template T *GetMutable() { if (!IsType()) { holder_.reset(new PlaceholderImp(new T())); } return static_cast(holder_->Ptr()); } template bool IsType() const { return holder_ != nullptr && holder_->Type() == typeid(T); } void Clear() { holder_.reset(); } std::type_index Type() const { return holder_->Type(); } private: struct Placeholder { Placeholder() = default; virtual ~Placeholder() = default; virtual const std::type_info &Type() const = 0; virtual void *Ptr() const = 0; }; template struct PlaceholderImp : public Placeholder { explicit PlaceholderImp(T *ptr) : ptr_(ptr), type_(typeid(T)) {} virtual const std::type_info &Type() const { return type_; } virtual void *Ptr() const override { return static_cast(ptr_.get()); } std::unique_ptr ptr_; const std::type_info &type_; }; Variant variant; std::unique_ptr holder_; friend class Scope; string name_; }; } // namespace framework } // namespace paddle_mobile