I'm trying to write a template function like this
template<typename T>
T doSomething() {
//Code
if (std::is_same<T, int>::value) {
return getInt(); // A library function returning an int
} else if (std::is_same<T, bool>::value) {
return getBool(); // A library function returning a bool
} else {
throw;
}
}
that calls different functions depending on the template parameter given and returns a value which, at runtime, is guaranteed to have the same type as T.
However, the compiler gives me this error: 'return': cannot convert from 'int' to 'T'
I guess I could use something like reinterpret_cast
, but this seems to be unsafe and bad practice in this scenario.
So, is there a way to return different types from a template function depending on the template parameter in C++?
So, is there a way to return different types from a template function depending on the template parameter in C++?
Yes, you can use C++17 constexpr if
template<typename T>
T doSomething() {
//Code
if constexpr (std::is_same<T, int>::value) {
return getInt(); // A library function returning an int
} else if constexpr (std::is_same<T, bool>::value) {
return getBool(); // A library function returning a bool
} else {
throw;
}
}