www.mooseframework.org
CastUniquePointer.h
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://www.mooseframework.org
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 #pragma once
11 
18 #include <memory>
19 
20 template <typename T_DEST, typename T_SRC, typename T_DELETER>
21 std::unique_ptr<T_DEST, T_DELETER>
22 dynamic_pointer_cast(std::unique_ptr<T_SRC, T_DELETER> & src)
23 {
24  if (!src)
25  return std::unique_ptr<T_DEST, T_DELETER>(nullptr);
26 
27  T_DEST * dest_ptr = dynamic_cast<T_DEST *>(src.get());
28  if (!dest_ptr)
29  return std::unique_ptr<T_DEST, T_DELETER>(nullptr);
30 
31  std::unique_ptr<T_DEST, T_DELETER> dest_temp(dest_ptr, std::move(src.get_deleter()));
32 
33  src.release();
34 
35  return dest_temp;
36 }
37 
38 template <typename T_DEST, typename T_SRC>
39 std::unique_ptr<T_DEST>
40 dynamic_pointer_cast(std::unique_ptr<T_SRC> & src)
41 {
42  if (!src)
43  return std::unique_ptr<T_DEST>(nullptr);
44 
45  T_DEST * dest_ptr = dynamic_cast<T_DEST *>(src.get());
46  if (!dest_ptr)
47  return std::unique_ptr<T_DEST>(nullptr);
48 
49  std::unique_ptr<T_DEST> dest_temp(dest_ptr);
50 
51  src.release();
52 
53  return dest_temp;
54 }
55 
std::unique_ptr< T_DEST, T_DELETER > dynamic_pointer_cast(std::unique_ptr< T_SRC, T_DELETER > &src)
These are reworked from https://stackoverflow.com/a/11003103.