perreal
perreal

Reputation: 97938

Transform a specific type of argument using templates

I want to have a utility function U that calls another function F after transforming a specific type of argument. The specific type of argument is vector<LibraryClass> and this is fixed. The transformation is from vector<LibraryClass> to special_vector<LibraryClass>.

The call will look like this:

vector<LibraryClass> a, c;
OtherType b, d, ...;
U(F, a, b, c, d, ...);

I want the above be equivalent to:

F(special_vector(a), b, special_vector(c), d, ...);

I really want is a very short solution. What do you think is the simplest way to implement this? I'm only interested in approaches not code.

Upvotes: 0

Views: 53

Answers (1)

Passer By
Passer By

Reputation: 21131

Fleshing out what Sam Varshavchik said

template<typename T>
T&& transform(T&& t) { return std::forward<T>(t); }

special_vector<LibraryClass> transform(const std::vector<LibraryClass>& v)
{
    return {v};
}

template<typename Fn, typename... Args>
void U(Fn f, Args&&... args)
{
    f(std::forward<Args>(transform(args))...);
}

You might want to either add more overloads for transform(std::vector<LibraryClass>&&) and all that, or SFINAE on the type.

Upvotes: 1

Related Questions