默认函数参数可以“填写”吗?扩展参数包? [英] Can default function arguments "fill in" for expanded parameter packs?
问题描述
以下代码无法编译:
#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)...);
似乎遵循了参数包最后的规则(至少在声明中)并在扩展后形成正确的函数调用: f2
可以使用1、2或3个参数来调用,因此参数太少
出现错误似乎严峻。它看起来也不像是推论问题(这是我的猜测-但由于错误消息而动摇了)
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'. 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.
您正在调用一个函数指针,该指针指向一个恰好需要3个参数的函数,该参数既不多也不少。
You are calling a function-pointer, which points to a function expecting exactly 3 arguments, neither more nor less.
当然,编译器会抱怨缺少的第三个。
Of course the compiler complains bitterly about the missing third one.
您可以使用可变的函子因为C ++ 14甚至是lambda :
You could do what you are trying to do there with a variadic functor, since C++14 even a lambda:
wrap([](auto&&... args){return f2(std::forward<decltype(args)>(args)...);}, 1, 'a');
这篇关于默认函数参数可以“填写”吗?扩展参数包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!