Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to call a lambda and pass the parameters separately.

e.g.:

#include <memory>

template<typename T, typename... TS>
T call(T (*)(TS...) f, TS&&... args) {
    return f(std::forward<TS...>(args...));
}

Thus I want to call this function like this:

call([](auto arg1, auto arg2){
    std::cout << arg1 << ", " << arg2 << std::endl;
}, 1, 2);

This should print out 1, 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
540 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can't just slap ... everywhere and hope it works. Understand how parameter packs work and use the correct syntax. Furthermore, the function call() should not return T. Use auto for the return type. And T is already the full type of f, you should not write T (*)(TS...). Here is the fixed version:

template<typename T, typename... TS>
auto call(T f, TS&&... args) {
    return f(std::forward<TS>(args)...);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...