for_each中使用的函数中的默认值

default values in functions used in for_each

本文关键字:函数 默认值 each for      更新时间:2023-10-16

我尝试将for_eachboost::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::localeboost::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); });

现在编译器将有足够的知识来使用默认参数。