Skip to content

Instantly share code, notes, and snippets.

@cqfd
Last active August 20, 2018 15:01
Show Gist options
  • Save cqfd/ec95134ddbded22bea8edfb85afc9866 to your computer and use it in GitHub Desktop.
Save cqfd/ec95134ddbded22bea8edfb85afc9866 to your computer and use it in GitHub Desktop.
Some Stan template examples.
// Variable templates
// There are some situations where they're not as flexible maybe as structs with boolean value members
// but kind of nice if all you're doing is type-level conditionals, since you don't need the ::value noise anymore.
template <typename T> constexpr bool is_constant = boost::is_convertible<T, double>::value;
// Variable templates work with partial specialization
template <typename T> constexpr bool is_constant_struct = is_constant<T>;
template <typename T> constexpr bool is_constant_struct<std::vector<T>> = is_constant_struct<T>;
template <typename T, int R, int C> constexpr bool is_constant_struct<Eigen::Matrix<T, R, C>> = is_constant_struct<T>;
template <typename T> constexpr bool is_constant_struct<Eigen::Block<T>> = is_constant_struct<T>;
// Variadic recursive variable templates!
template <typename...> constexpr bool contains_nonconstant_struct = false;
template <typename T, typename... Ts> constexpr bool contains_nonconstant_struct<T, Ts...> = !is_constant_struct<T> || contains_nonconstant_struct<Ts...>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment