Vik*_*tor 7 c++ perfect-forwarding c++11
从我的角度来看,我发现了很奇怪的行为:函数默认参数不能在下面的代码中转发.
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
}
Run Code Online (Sandbox Code Playgroud)
Clang报告:错误:函数调用的参数太少,预期为1,有0个GCC,VC报告相同的错误.
任何人都可以解释一下吗?
Bri*_*ian 11
Test是一个总是需要一个参数的函数.如果Test通过name调用其带有default参数的声明是可见的,则编译器将隐式地将默认参数添加到调用中.但是,一旦Test转换为指针或函数引用,默认参数信息就不再可见.
这可以通过创建一个函数来解决,该函数确实需要零个或一个参数,并将该信息编码到其类型中,因此它不能被销毁,如下所示:
struct Test {
void operator()(int) { /* ... */ }
void operator()() { operator(int{}); }
} test;
// ...
Foo(test, 0); // ok
Foo(test); // ok
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
256 次 |
| 最近记录: |