Search code examples
c++c++11templatesvariadic-templates

Convert arguments of variadic function


This is probably a newbie question but I thought it might be interesting. Let's say I have this function:

template <typename First, typename... T>
int ComputeSomething(const First& f, const T&... t);

I would like to write a second function that calls the one above in the general case, but converts the arguments when First and T are of type float, i.e., it calls a Convert function on each argument:

long Convert(float f);

template <typename First, typename... T>
int MyFun(const First& f, const T&... t) {
  return ComputeSomething(f, t...);
}

// This is what I would like:
int MyFun(const float& f, const float& t...) {
  return ComputeSomething(Convert(f), Convert(t)...);
}

How can I achieve that?


Solution

  • Add a transparent Convert overload, so that non-floats are bypassed (that is, you can have mixed types of arguments):

    template <typename First, typename... T>
    int ComputeSomething(const First& f, const T&... t);
    
    long Convert(float f);
    
    // Transparent converter
    template <typename T>
    T&& Convert(T&& t) { return std::forward<T>(t); }
    
    template <typename First, typename... Ts>
    int MyFun(const First& f, const Ts&... t)
    {
        return ComputeSomething(Convert(f), Convert(t)...);
    }
    

    DEMO