I have a template function that I would like to only work with a specific list of types.
template <class T> void foo(const T f) {/*do stuff with f*/}
int main() {
string A= "Hello world";
char B[10] = "Hello world";
Int C = 69;
foo(A); //should work here
foo(B); //and here
foo(C); //but it should give an error here, preferably while it is compiling
return 0;
}
I expect it to work if I call it with a char[] or with a string, but give an error (possibly while it's compiling, but during runtime works too) when I try to call it with an INT type.
For your particular case, I would overload the function foo
instead of using a template. This ensures you can only have one of those two types, and with those two types in particular it is quite simple to overload:
void foo(const char* s) {
// do work with s
}
void foo(const std::string& s) {
foo(s.c_str()); // use the other overload for const char*
}
SFINAE might help:
template <class T, std::enable_if_t<!std::is_same<int, T>::value, int> = 0>
void foo(const T f) {/*do stuff with f*/}
or
template <class T,
std::enable_if_t<std::is_same<std::string, T>::value
|| std::is_same<const char*, T>::value, int> = 0>
void foo(const T f) {/*do stuff with f*/}
Adjust the condition to your needs.
or static_assert
:
template <class T>
void foo(const T f) {
static_assert(std::is_same<std::string, T>::value
|| std::is_same<const char*, T>::value, "Incorrect type");
/*do stuff with f*/
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With