Skip to content

Instantly share code, notes, and snippets.

@moleike
Created November 19, 2015 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moleike/bc5062909f5e45f3f474 to your computer and use it in GitHub Desktop.
Save moleike/bc5062909f5e45f3f474 to your computer and use it in GitHub Desktop.
tag dispatching based on type traits
#include <iostream>
struct fast_speed_tag {};
struct slow_speed_tag {};
template <typename T>
struct traits { // default
typedef slow_speed_tag speed;
};
template <>
struct traits<int> { // we would do the same for long etc
typedef fast_speed_tag speed;
};
template <typename T>
void work_dispatch (const T &val, const slow_speed_tag&) {
std::cout << "slow" << std::endl;
}
template <typename T>
void work_dispatch (const T &val, const fast_speed_tag&) {
std::cout << "fast" << std::endl;
}
template <typename T>
void work (const T &val) {
work_dispatch(val, typename traits<T>::speed());
}
int main () {
int x;
float y;
work(x); // fast
work(y); // slow
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment