Is it possible for a function to only accept a limited set of types for a given argument?
c++, c++11, function, polymorphism, templates
Solution
A simple solution using `enable_if` and `is_same`:
template<typename T>
typename std::enable_if<
std::is_same<T, int>::value ||
std::is_same<T, char>::value,
T>::type
myFunc(T data) { ... }
As the predicate on `T` becomes more complex (for example, do you just allow `string` and `wstring`, or other specializations of `basic_string`?) you may start to want to write more complex predicate metafunctions; but for now, a simple expression is likely to suffice.
Problem
I know how to do it with any data type with template: ``` template<typename T> T myFunc(T data) { ... } ``` But is there a way to narrow the set of allowed types to for example `int` and `char` or `std::string` and `std::wstring`, so the compiler would throw an error when encountering not allowed argument type and I will get error on compile time instead of run time ? edit: Big thanks to ecatmur, now I understand the whole concept. ``` template<typename itemA_type, typename itemB_type> typename std::enable_if< ( std::is_same<itemA_type, int>::value || std::is_same<itemA_type, char>::value) && ( std::is_same<itemB_type, std::string>::value || std::is_same<itemB_type, std::wstring>::value || std::is_same<itemB_type, const char*>::value || std::is_same<itemB_type, const wchar_t*>::value ) , void >::type myFunction(itemA_type itemA, itemB_type itemB) { using namespace std; cout << itemA << itemB << endl; } ```