简体   繁体   English

默认函数参数可以“填充”扩展参数包吗?

[英]Can default function arguments “fill in” for expanded parameter packs?

The following code fails to compile :以下代码无法编译

#include <iostream>

template<typename F, typename ...Args>
static auto wrap(F func, Args&&... args)
{
    return func(std::forward<Args>(args)...);
}

void f1(int, char, double)
{
    std::cout << "do nada1\n"; 
}

void f2(int, char='a', double=0.)
{
    std::cout << "do nada2\n"; 
}

int main()
{
    wrap(f1, 1, 'a', 2.); 
    wrap(f2, 1, 'a'); 
}
g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out

main.cpp: In instantiation of 'auto wrap(F, Args&& ...) [with F = void(*)(int, char, double); Args = {int, char}]':
main.cpp:22:20:   required from here
main.cpp:6:44: error: too few arguments to function
     return func(std::forward<Args>(args)...);

It seems that the rule about "parameter packs being last" is followed (at least in the declaration) and after the expansion a correct function call should be formed : f2 can either be called with 1, 2 or 3 arguments so the too few arguments being an error seems 'harsh'.似乎遵循了关于“参数包在最后”的规则(至少在声明中)并且在扩展之后应该形成正确的函数调用: f2可以用 1、2 或 3 个参数调用,因此too few arguments成为一个错误似乎是“严厉的”。 It also doesn't look like a deduction problem (which would be my guess - but got shaky due to the error message)它看起来也不像是一个扣除问题(这是我的猜测 - 但由于错误消息而不稳定)

Is this a missing feature or there's a violation from the Standard's point of view ?从标准的角度来看,这是缺失的功能还是存在违规行为?

You aren't calling a function with default-arguments from the template.您不是从模板中调用带有默认参数的函数。

You are calling a function-pointer, which points to a function expecting exactly 3 arguments, neither more nor less.您正在调用一个函数指针,该函数指针指向一个需要 3 个参数的函数,既不多也不少。

Of course the compiler complains bitterly about the missing third one.当然,编译器会痛心地抱怨缺少第三个。

You could do what you are trying to do there with a variadic functor, since C++14 even a lambda :你可以用可变参数函子做你想做的事情,因为 C++14 甚至是 lambda

wrap([](auto&&... args){return f2(std::forward<decltype(args)>(args)...);}, 1, 'a'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM