【问题标题】:Can default function arguments "fill in" for expanded parameter packs?默认函数参数可以“填充”扩展参数包吗?
【发布时间】:2015-01-28 16:28:58
【问题描述】:

以下代码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)...);

似乎遵循了关于“参数包最后”的规则(至少在声明中)并且在扩展之后应该形成正确的函数调用:f2 可以用 1、2 或 3 个参数调用所以too few arguments 是一个错误似乎“苛刻”。它看起来也不像 deduction problem(这是我的猜测 - 但由于错误消息而变得不稳定)

这是缺少的功能还是从标准的角度来看存在违规行为?

【问题讨论】:

  • 它与 clang 3.5 引发类似的错误
  • VS2013 给出这个:main.cpp(7): error C3551: expected a trailing return type

标签: c++ c++11 parameter-passing variadic-templates c++14


【解决方案1】:

您没有从模板调用带有默认参数的函数。

您正在调用一个函数指针,它指向一个函数,该函数需要正好 3 个参数,不多也不少。

编译器当然会抱怨缺少第三个。

你可以用可变参数函子 since C++14 even a lambda 来做你想做的事情:

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

【讨论】:

  • return f2(std::forward&lt;decltype(args)&gt;(args)...);
  • .. 现在void(*)(int, char, double) 中的* 突然写成了26 fond
猜你喜欢
  • 2015-05-19
  • 2011-04-01
  • 2012-07-25
  • 2011-04-18
  • 2014-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多