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