variable.h 2.0 KB
Newer Older
Y
Yi Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
  Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
  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

Y
Yi Wang 已提交
15 16
#include <memory>
#include <typeindex>
Y
Yi Wang 已提交
17 18
#include <typeinfo>

Y
Yi Wang 已提交
19 20
#include "paddle/platform/assert.h"

Y
Yi Wang 已提交
21 22 23 24 25 26 27
namespace paddle {
namespace framework {

class Variable {
 public:
  template <typename T>
  const T& Get() const {
Y
Yi Wang 已提交
28 29 30
    PADDLE_ASSERT(holder_ != nullptr);
    PADDLE_ASSERT(std::type_index(typeid(T)) ==
                  std::type_index(holder_->Type()));
Y
Yi Wang 已提交
31 32 33 34 35
    return *static_cast<const T*>(holder_->Ptr());
  }

  template <typename T>
  T* GetMutable() {
Y
Yi Wang 已提交
36 37 38
    if (holder_ == nullptr ||
        std::type_index(typeid(T)) != std::type_index(holder_->Type())) {
      holder_.reset(new PlaceholderImpl<T>(new T()));
Y
Yi Wang 已提交
39
    }
Y
Yi Wang 已提交
40
    return static_cast<T*>(holder_->Ptr());
Y
Yi Wang 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  }

 private:
  struct Placeholder {
    virtual ~Placeholder() {}
    virtual const std::type_info& Type() const = 0;
    virtual void* Ptr() const = 0;
  };

  // Placeholder hides type T, so it doesn't appear as a template
  // parameter of Variable.
  template <typename T>
  struct PlaceholderImpl : public Placeholder {
    PlaceholderImpl(T* ptr) : ptr_(ptr), type_(typeid(T)) {}

    virtual const std::type_info& Type() const { return type_; }
Y
Yi Wang 已提交
57
    virtual void* Ptr() const { return static_cast<void*>(ptr_.get()); }
Y
Yi Wang 已提交
58

Y
Yi Wang 已提交
59
    std::unique_ptr<T> ptr_;
Y
Yi Wang 已提交
60 61 62
    const std::type_info& type_;
  };

Y
Yi Wang 已提交
63 64
  std::unique_ptr<Placeholder>
      holder_;  // pointers to a PlaceholderImpl object indeed.
Y
Yi Wang 已提交
65 66 67 68
};

}  // namespace framework
}  // namespace paddle