我尝试将 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
,您将始终需要填充这两个参数。
关于c++ - for_each 中使用的函数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18528475/