Skip to content

Instantly share code, notes, and snippets.

@nthery
Created November 12, 2020 06:13
Show Gist options
  • Save nthery/9702d9f41d3d1bb0034448558921b982 to your computer and use it in GitHub Desktop.
Save nthery/9702d9f41d3d1bb0034448558921b982 to your computer and use it in GitHub Desktop.
covariance and contravariance in std::function
// Covariance and contra-variance in std::function
// See
// https://quuxplusone.github.io/blog/2019/01/20/covariance-and-contravariance/
#include <functional>
struct B {};
struct D : B {};
// std::function is covariant on return types.
// B -----> B(void)
// ^ ^
// | |
// D -----> D(void)
B give_b();
D give_d();
std::function<B(void)> co = give_d;
// std::function<D(void)> contra_bad = give_b;
// std::function is contravariant on parameters.
// B -----> void(B)
// ^ |
// | V
// D -----> void(D)
void take_b(B);
void take_d(D);
std::function<void(D)> contra = take_b;
// std::function<void(B)> co_bad = take_d;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment