[英]Dynamically creating function parameters that are perfectly forwarded in C++
[英]Why function default parameters cannot be perferct forwarded in C++?
从我的角度来看,我发现了很奇怪的行为:函数默认参数不能在下面的代码中转发。
void Test(int test = int{}) {}
template<typename F, typename ...Args>
void Foo(F&& f, Args&&... args)
{
std::forward<F>(f)(std::forward<Args>(args)...);
}
int main()
{
Foo(Test, 0); // This compiles
Foo(Test); // This doesn't compile
}
Clang报告:错误:函数调用的参数太少,预期为1,有0个GCC,VC报告相同的错误。
任何人都可以解释一下吗?
代码在这里: http : //rextester.com/live/JOCY22484
Test
是一个总是需要一个参数的函数。 如果在按名称调用Test
时,其带有默认参数的声明是可见的,则编译器将隐式地将默认参数添加到调用中。 但是,一旦将Test
转换为指针或函数引用,默认参数信息就不再可见。
这可以通过创建一个函数来解决,该函数确实需要零个或一个参数,并将该信息编码到其类型中,因此它不能被销毁,如下所示:
struct Test {
void operator()(int) { /* ... */ }
void operator()() { operator(int{}); }
} test;
// ...
Foo(test, 0); // ok
Foo(test); // ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.