Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify variable #2647

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions paddle/framework/variable.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,42 +25,37 @@ class Variable {
public:
template <typename T>
const T& Get() const {
PADDLE_ASSERT(IsType<T>());
return *static_cast<const T*>(holder_->Ptr());
auto holder = dynamic_cast<PlaceholderImpl<T>*>(holder_.get());
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why use dynamic_cast?

PADDLE_ASSERT(holder != nullptr);
return *(holder->Ptr());
}

template <typename T>
T* GetMutable() {
if (!IsType<T>()) {
holder_.reset(new PlaceholderImpl<T>(new T()));
}
return static_cast<T*>(holder_->Ptr());
return dynamic_cast<PlaceholderImpl<T>*>(holder_.get())->Ptr();
}

template <typename T>
bool IsType() const {
return holder_ != nullptr &&
std::type_index(typeid(T)) == std::type_index(holder_->Type());
return dynamic_cast<PlaceholderImpl<T>*>(holder_.get()) != nullptr;
}

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_; }
virtual void* Ptr() const { return static_cast<void*>(ptr_.get()); }
PlaceholderImpl(T* ptr) : ptr_(ptr) {}
T* Ptr() const { return ptr_.get(); }

std::unique_ptr<T> ptr_;
const std::type_info& type_;
};

std::unique_ptr<Placeholder>
Expand Down