Skip to content

Instantly share code, notes, and snippets.

@insertinterestingnamehere
Created September 15, 2015 17:33
Show Gist options
  • Save insertinterestingnamehere/db6ef7931b004a7d60f8 to your computer and use it in GitHub Desktop.
Save insertinterestingnamehere/db6ef7931b004a7d60f8 to your computer and use it in GitHub Desktop.
This shows how to enable a template for an explicit list of types.
#include <iostream>
#include <type_traits>
template<typename T, typename... UsableTypes>
struct SearchImpl : std::is_same<T, UsableTypes>...
{
};
template<typename T, typename... UsableTypes>
struct Search : std::is_base_of<std::true_type, SearchImpl<T, UsableTypes...>>::type
{
};
// Enable a given template only for a given list of types.
// Works assuming all the types given are unique
template<typename T, typename... UsableTypes>
struct enable_for : std::enable_if<Search<T, UsableTypes...>::value, int>
{
};
// Example:
template<typename T, typename enable_for<T, char, short, int, long, long long>::type = 0>
void print_classification(T) {
std::cout << "This is an integral type" << std::endl;
}
template<typename T, typename enable_for<T, double, float>::type = 0>
void print_classification(T) {
std::cout << "This is a floating point type" << std::endl;
}
template<typename T, typename enable_for<T, double, float>::type = 0,
typename U, typename enable_for<U, char, short, int, long, long long>::type = 0>
void print_classification(T, U) {
std::cout << "float then int" << std::endl;
}
template<typename T, typename enable_for<T, char, short, int, long, long long>::type = 0,
typename U, typename enable_for<U, double, float>::type = 0>
void print_classification(T, U) {
std::cout << "int then float" << std::endl;
}
template<typename T, typename enable_for<T, char, short, int, long, long long>::type = 0,
typename U, typename enable_for<U, char, short, int, long, long long>::type = 0>
void print_classification(T, U) {
std::cout << "both int" << std::endl;
}
template<typename T, typename enable_for<T, double, float>::type = 0,
typename U, typename enable_for<U, double, float>::type = 0>
void print_classification(T, U) {
std::cout << "both float" << std::endl;
}
int main() {
std::cout << Search<int, double, int>::value << std::endl;
print_classification('a');
print_classification((short)2);
print_classification(2);
print_classification(2l);
print_classification(2ll);
print_classification(2.);
print_classification(2.0f);
print_classification(2., 3);
print_classification(3, 2.);
print_classification(2, 2);
print_classification(2., 2.);
int a = 2;
int &b = a;
int &&c = 2;
print_classification(a);
print_classification(b);
print_classification(c);
return 0;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment