Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using type passed as a template in C++

Tags:

c++

templates

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.

like image 691
moatPylon Avatar asked Dec 30 '25 19:12

moatPylon


2 Answers

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".

like image 150
Georg Fritzsche Avatar answered Jan 01 '26 09:01

Georg Fritzsche


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);
}
like image 31
Tyler McHenry Avatar answered Jan 01 '26 10:01

Tyler McHenry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!