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) can
14 /// reasonably discard any supplemental scalar data, e.g., the derivatives of an
15 /// AutoDiffScalar, and (2) is reasonable to fail at runtime if the extraction
16 /// fails.
17 ///
18 /// The default implementation throws an exception. ScalarTypes that can hold a
19 /// numeric value must overload this method to provide an appropriate
20 /// extraction. An overload for double is already provided.
21 ///
22 /// See autodiff_overloads.h to use this with Eigen's AutoDiffScalar.
23 /// See symbolic_expression.h to use this with symbolic::Expression.
24 /// See number_traits.h for specifying which ScalarTypes are numeric.
25 template <typename T>
26 double ExtractDoubleOrThrow(const T&) {
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:105
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.
Definition: autodiff_overloads.h:145
is_numeric is true for types that are on the real line.
Definition: number_traits.h:31