for_each中使用的函数中的默认值
default values in functions used in for_each
我尝试将for_each
与boost::trim
一起使用。首先,我使用了错误的代码
std::for_each(v.begin(),v.end(),&boost::trim<std::string>));
// error: too few arguments to function
然后我用这个修复了(在线阅读)
std::for_each(v.begin(),v.end()
,boost::bind(&boost::trim<std::string>,_1,std::locale()));
编译器在需要将此函数传递给for_each
时的工作方式。我认为由于std::locale
是boost::trim
的第二个输入参数的默认参数,所以我的代码应该已经工作了。
当调用函数时,会应用默认参数,但它们不构成函数签名的一部分。特别是,当您通过函数指针调用函数时,通常会丢失默认参数可用的信息:
void (*f)(int, int);
void foo(int a, int b = 20);
void bar(int a = 10, int = -8);
f = rand() % 2 == 0 ? foo : bar;
f(); // ?
结果是,要在f
上使用bind
,您总是需要填充这两个参数。
您可以始终使用lambda:编写它
std::for_each(v.begin(), v.end(), [](std::string & s) { boost::trim(s); });
现在编译器将有足够的知识来使用默认参数。
相关文章:
- 具有默认值的引用获取函数
- 如何使用默认值为构造函数中的枚举赋值?
- 变量始终在函数中重置为默认值
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 函数不返回默认值
- 在 c++ 中,如果我创建一个接受一个具有默认值的参数的构造函数 - 它会用作默认(空)构造函数吗?
- 为什么 std::move 不将默认移动构造函数中的源变量更改为默认值?
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 在子类函数覆盖中省略具有默认值的参数
- 函数作为具有默认值的参数
- 将复制构造函数设置为默认值在继承自 QObject 时不起作用
- 当 T 不可默认构造时,构造函数初始值设定项列表中 std::array<T,N> 的初始化
- 未设置默认值的 c++ 构造函数
- C++中出现意外的编译错误:将默认值传递给函数参数
- 如何从类构造函数传递值C++作为此类方法的默认参数?
- 组合 std::vector 默认值和填充构造函数
- 在结构C++,构造函数中的默认值和默认参数有什么区别
- 在c++中设置构造函数默认值
- 指针对成员函数默认值出现与CRTP相关的编译器错误
- C++构造函数默认值头文件