Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass first N args to a C++ function

I've got a function like this:

void loadData(std::function<void (std::string, std::string, std::string)> callback)
{
    // data loading stuff
    callback(body, subject, header);
}

The problem is I'm not necessarily need to use subject and header in my callback function. Now I'm handling it this way:

loadData([](std::string body, std::string, std::string){
    std::cout << body;
})

I want to replace it with

loadData([](std::string body){
    std::cout << body;
})

and automatically pass to callback function as many arguments as it able to accept. I don't want to manually overload loadData function for all 3 possible argument counts. I also don't want to use any more complicated lambda syntax on the calling site because my library should be clear for others to use. Is this possible using C++ STL and Boost?

like image 501
Denis Sheremet Avatar asked Oct 16 '17 17:10

Denis Sheremet


1 Answers

What about ignoring the following arguments using ... ?

loadData([](std::string body, ...){
    std::cout << body;
})


As pointed by StoryTeller (thanks!) the use of ellipsis can be unsupported for non trivial types (see [expr.call]p9 for more details).

To avoid this problem, if you can use C++14, you can use auto ... (better auto && ... to avoid unnecessary copies; thanks Yakk).

loadData([](std::string body, auto && ...){
    std::cout << body;
})
like image 80
max66 Avatar answered Nov 15 '22 10:11

max66