Question

My problem is the following: I have a class declared as such:

template<typename ReturnType, typename... Args>
class API
{
    ReturnType operator()(Args... args)
    {
       // Get argument 0
       // Get argument 1
    }
};

I am in need of getting the arguments on by one, and so far the only way I've come up to (but I can not get it to work) is using std::get, as such:

std::get<0>(args);

Of course, this leads to a lot of errors. I am new to variadic templates (and to C++11 at all) so I am quite lost at this point.

How could I get those arguments one by one? Any help will be appreciated.

Was it helpful?

Solution

Capture the args in a temporary tuple (Live at Coliru):

ReturnType operator()(Args... args)
{
   static_assert(sizeof...(args) >= 3, "Uh-oh, too few args.");
   // Capture args in a tuple
   auto&& t = std::forward_as_tuple(args...);
   // Get argument 0
   std::cout << std::get<0>(t) << '\n';
   // Get argument 1
   std::cout << std::get<1>(t) << '\n';
   // Get argument 2
   std::cout << std::get<2>(t) << '\n';
}

std::forward_as_tuple uses perfect forwarding to capture references to the args, so there should be no copying.

OTHER TIPS

You can use recursion.

Here's an example:

#include <iostream>

template<typename ReturnType>
class API {
public:
    template<typename Arg>
    ReturnType operator()(Arg&& arg) {
        // do something with arg
        return (ReturnType) arg;
    }

    template<typename Head, typename... Tail>
     ReturnType operator()(Head&& head, Tail&&... tail) {
        // do something with return values
        auto temp = operator()(std::forward<Head>(head));
        return temp + operator()(std::forward<Tail>(tail)...);
    }
};

int main() {
    API<int> api;
    auto foo = api(1, 2l, 2.0f);
    std::cout << foo;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top