Vcsn  2.3
Be Rational
cast.hh
Go to the documentation of this file.
1 #pragma once
2 
3 #include <iostream>
4 #include <vcsn/misc/raise.hh>
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  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  std::shared_ptr<T>
58  cast(std::shared_ptr<U> t)
59  {
60  if (!t)
61  error<std::shared_ptr<T>, std::shared_ptr<U>>("down_casting nullptr");
62  std::shared_ptr<T> res = std::dynamic_pointer_cast<T>(t);
63  if (!res)
64  error<std::shared_ptr<T>, std::shared_ptr<U>>("failed down_cast");
65  return res;
66  }
67  };
68  }
69 }
70 #endif
71 
72 namespace vcsn
73 {
74  namespace detail
75  {
78  template <typename T>
79  T lexical_cast(const std::string& str)
80  {
81  T res;
82  std::istringstream iss;
83  iss.str(str);
84  if (!(iss >> res))
85  raise("invalid value: ", str);
86  VCSN_REQUIRE(iss.peek() == EOF,
87  ": invalid value: ", str,
88  ", unexpected ", str_escape(iss.peek()));
89  return res;
90  }
91  }
92 }
std::ostream & str_escape(std::ostream &os, const std::string &str, const char *special=nullptr)
Output a string, escaping special characters.
Definition: escape.cc:51
void error(const char *msg)
Definition: cast.hh:34
A functor that captures the current location (to report errors), and provides "cast".
Definition: cast.hh:24
down_caster(const char *f, int l)
Definition: cast.hh:26
return res
Definition: multiply.hh:398
std::shared_ptr< T > cast(std::shared_ptr< U > t)
Special case for shared_ptr.
Definition: cast.hh:58
Definition: a-star.hh:8
#define VCSN_REQUIRE(Cond,...)
A macro similar to require.
Definition: raise.hh:111
T lexical_cast(const std::string &str)
String to templated type T conversion.
Definition: cast.hh:79
const char * file
Definition: cast.hh:29