Is it possible to actually use the type passed as a template for control flow? I'd like to write a function that uses templates, which in turn calls another function based on the type passed:
template <class T> void test_function (T var)
{
//Do stuff
if (T == char) {
bar (var);
} else {
foo (var);
}
//Do even more stuff
}
If not, I'll have to fallback to enums...
Edit: All the answers up to now advise me to use template specialization. I wasn't very specific, but this is the same as not using templates at all because for every different type there's a single, different function call.
You usually use specialization for that:
template<class T> void forward(T t) {
// ...
}
template<> void forward<char>(char c) {
// ...
}
template<class T> void test(T t) {
forward<T>(t);
}
This gives you effectively "compile-time branching".
It is possible to do this, but it is almost never a good idea to do it. A better idea is just to factor out the common bits and provide an overload for the function for those specific types, e.g.
template <class T> void test_function_prologue (T var)
{
//Do stuff
}
template <class T> void test_function_epilogue (T var)
{
//Do even more stuff
}
template <class T> void test_function (T var)
{
test_function_prologue(var);
foo (var);
test_function_epilogue(var);
}
void test_function (char var)
{
test_function_prologue(var);
bar (var);
test_function_epilogue(var);
}
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