Drake
extract_double.h
Go to the documentation of this file.
1 #pragma once
2
3 #include <stdexcept>
4
7
8 namespace drake {
9
10 /// Converts a ScalarType value to a double, failing at runtime (not compile
11 /// time) if the type cannot be converted to a double.
12 ///
13 /// This function is useful for writing ScalarType-generic code that (1) is
14 /// only intended to be used on numeric types, (2) can reasonably discard any
15 /// supplemental scalar data, e.g., the derivatives of an AutoDiffScalar, and
16 /// (3) is reasonable to fail at runtime if called with a non-numeric
17 /// ScalarType.
18 ///
19 /// The default implementation throws an exception. ScalarTypes that are
20 /// numeric must overload this method to provide an appropriate extraction.
21 /// An overload for double is already provided.
22 ///
23 /// See autodiff_overloads.h to use this with Eigen's AutoDiffScalar.
24 /// See number_traits.h for specifying which ScalarTypes are numeric.
25 template <typename T>
26 double ExtractDoubleOrThrow(const T& scalar) {
27  static_assert(!is_numeric<T>::value,
28  "Numeric scalar types should overload this function");
29  throw std::runtime_error(NiceTypeName::Get<T>() +
30  " cannot be converted to a double");
31 }
32
33 /// Returns @p scalar as a double. Never throws.
34 inline double ExtractDoubleOrThrow(double scalar) { return scalar; }
35
36 } // namespace drake
Definition: automotive_demo.cc:88
This file contains traits for number (scalar) types.
double ExtractDoubleOrThrow(const Eigen::AutoDiffScalar< DerType > &scalar)
Returns the autodiff scalar&#39;s value() as a double.