Vcsn  2.0
Be Rational
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
cast.hh
Go to the documentation of this file.
1 #ifndef VCSN_MISC_CAST_HH
2 # define VCSN_MISC_CAST_HH
3 
4 # include <iostream>
5 
6 # ifdef NDEBUG
7 # define down_cast static_cast
8 # define down_pointer_cast std::static_pointer_cast
9 # else
10 
11 // We want to support the "down_cast<FOO>(BAR)" syntax (with a pair of
12 // <> and of ()). So expand "down_cast" into a templated function.
13 // Actually, make it a functor that can be given the current location.
14 #define down_cast \
15  ::vcsn::detail::down_caster(__FILE__, __LINE__).cast
16 #define down_pointer_cast down_cast
17 
18 namespace vcsn
19 {
20  namespace detail
21  {
24  struct down_caster
25  {
26  down_caster(const char* f, int l)
27  : file(f), line(l)
28  {}
29  const char* file;
30  int line;
31 
32  template <typename T, typename U>
33  void
34  error(const char* msg)
35  {
36  std::cerr
37  << file << ':' << line << ": " << msg
38  << " from " << typeid(U).name() << " to " << typeid(T).name()
39  << std::endl;
40  abort();
41  }
42 
43  template <typename T, typename U>
44  inline
45  T
46  cast(U t)
47  {
48  if (!t)
49  error<T, U>("down_casting nullptr");
50  T res = dynamic_cast<const T>(t);
51  if (!res)
52  error<T, U>("failed down_cast");
53  return res;
54  }
55 
57  template <typename T, typename U>
58  inline
59  std::shared_ptr<T>
60  cast(std::shared_ptr<U> t)
61  {
62  if (!t)
63  error<std::shared_ptr<T>, std::shared_ptr<U>>("down_casting nullptr");
64  std::shared_ptr<T> res = std::dynamic_pointer_cast<T>(t);
65  if (!res)
66  error<std::shared_ptr<T>, std::shared_ptr<U>>("failed down_cast");
67  return res;
68  }
69  };
70  }
71 }
72 #endif
73 
74 #endif // !VCSN_MISC_CAST_HH
down_caster(const char *f, int l)
Definition: cast.hh:26
A functor that captures the current location (to report errors), and provides "cast".
Definition: cast.hh:24
const char * file
Definition: cast.hh:29
void error(const char *msg)
Definition: cast.hh:34
std::shared_ptr< T > cast(std::shared_ptr< U > t)
Special case for shared_ptr.
Definition: cast.hh:60