Variadic template, function as argument

流过昼夜 提交于 2020-01-16 16:16:06

问题


I would like to use a function as argument in a variadic template, why does the following not work? How do I make it work?

template<typename F, typename... Args>
F test(F f, const Args&&... args) {
return f(std::forward<Args>(args)...);
}

int simple(int i) { 
    return i; 
}


int main()
{
    std::cout << test(simple, 2); // error, 'std::forward': none of the 2 overloads could convert all the argument types
}

回答1:


There are a couple of problems with your code.

First of all, you should use forwarding references, so you need to change const Args&&... to Args&&....

Then, test does not have to return F. So it is reasonable to use decltype(auto) here.

In addition to that, it makes sense to forward f too.

The fixed version might look like this:

template<typename F, typename... Args>
decltype(auto) test(F&& f, Args&&... args) {
    return std::forward<F>(f)(std::forward<Args>(args)...);
}

WANDBOX EXAMPLE




回答2:


The first problem is the return type. Your test function returns F which is a function pointer. Instead change it to auto to automatically deduce the return type.

The second issue is that std::forward requires a non-const reference.

You might use trailing return type:

template<typename F, typename... Args>
auto test(F f, Args&&... args) -> decltype(f(std::forward<Args>(args)...)) {
    return f(std::forward<Args>(args)...);
}

But decltype(auto) (C++14 required) is a simpler solution:

template<typename F, typename... Args>
decltype(auto) test(F f, Args&&... args) {
    return f(std::forward<Args>(args)...);
}


来源:https://stackoverflow.com/questions/45352511/variadic-template-function-as-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!