Another common solution is to use std :: disjunction (C ++ 17) to execute logical ORs. Valid types are specified as template parameters when calling your test function, or you can define a typedef for specialization.
#include <iostream> #include <type_traits> template <typename... Ts, typename T, typename std::enable_if<std::disjunction<std::is_same<T, Ts>...>::value>::type* = nullptr> void test(T i) { std::cout << "test\n"; } int main() { int i = 4; test<int, float, const char*>(i); //test<float, const char*>(i); // compile fails since no int // or use a typedef for the specialization typedef void (*specialized_t)(int); constexpr specialized_t test2 = &test<int, float, const char*>; test2(i); }
run the code
source share