del del - 3 months ago 16
C++ Question

Conditional code generation in template function

I'm trying to write a single template function that will work fine in both of these cases. I have two functions:

template <typename T>
Check(T&)

template <typename U, typename V>
Check(U&, V&)


I have a function which I would like to write a single implementation of, where in case of any other type than a pair, I want it to call Check(T&) and if we have a std::pair, then it should call the two parameter variant of Check. In other words, code like:

void SomeFunction() {
...
if (type(x) is std::pair<U,V>)
Check(x.first, x.second);
else
Check(x);
...
}


Is there some way of accomplishing this behavior using template magic? The code should preferably work with C++11. I own the code for the Check functions and they are internal to the class, so I can tweak their interface if necessary.

Answer

Did you mean something like this? It provides an overload which works only for pairs and calls the 2 argument function.

#include <iostream>
#include <utility>

template <typename T>
void Check(T& t)
{
    std::cout << "single argument version " << t << '\n';
}

template <typename U, typename V>
void Check(U& u, V& v)
{
    std::cout << "pair version " << u << " and " << v << '\n';
}

template<typename T>
void call(T& t)
{
    Check(t);
}

template<typename T, typename U>
void call(const std::pair<T, U>& t)
{
    Check(t.first, t.second);
}

int main()
{
    int i = 1;

    call(i);
    call(std::pair<int, char>(2, 'c'));
}