Skip to content

Instantly share code, notes, and snippets.

@csullivan
Last active July 28, 2016 16:04
Show Gist options
  • Save csullivan/cc860de2f4e994ff38a91a57cb8936f7 to your computer and use it in GitHub Desktop.
Save csullivan/cc860de2f4e994ff38a91a57cb8936f7 to your computer and use it in GitHub Desktop.
An example using c++ constraints and concept templates
// Function template constraint (implicit or "ad-hoc")
template<typename T> requires
requires (T a) { a + a; } &&
requires (T b) { b * b; } &&
requires (T c) { sqrt(c); }
T Magnitude(vector<T>&& vec) {
T sum;
for (auto& const i : vec) { sum += i*i; }
return sqrt(sum);
}
// Explicit requirements (not "ad-hoc") which can be reused in function templates
template<typename T>
concept bool Addable = requires(T a) { a + a; };
template<typename T>
concept bool Multipliable = requires(T a) { a * a; };
template<typename T>
concept bool Rootable = requires(T a) { sqrt(a); };
template<typename T> requires Addable<T> && Multipliable<T> && Rootable<T>
T Magnitude(vector<T>&& vec) {
T sum;
for (auto& const i : vec) { sum += i*i; }
return sqrt(sum);
}
///// Type constraints
// We can also require a template type T to have certain properties (or traits)
template<typename T> concept bool VectorType = requires () {
typename T::elements; // required member
typename Matrix<T>; // required class template specialization
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment