C++ 中使用的函数中的默认值

C++ 中使用的函数中的默认值,c++,algorithm,boost,stl,function-pointers,C++,Algorithm,Boost,Stl,Function Pointers,我尝试将与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::trim)); //错误:参数太少,无法正常工作 然后我用这个修复了(在线阅读) std::for_each(v

我尝试将
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::trim));
//错误:参数太少,无法正常工作
然后我用这个修复了(在线阅读)

 std::for_each(v.begin(),v.end()
              ,boost::bind(&boost::trim<std::string>,_1,std::locale()));
std::for_each(v.begin(),v.end())
,boost::bind(&boost::trim,_1,std::locale());

当编译器需要为每个将此函数传递到
时,它是如何工作的。我认为因为
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
,始终需要填充这两个参数。

在调用函数时应用默认参数,但它们不构成函数签名的一部分。特别是,当您通过函数指针调用函数时,通常会丢失哪些默认参数可用的信息:

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); });

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

您始终可以使用lambda编写它:

std::for_each(v.begin(), v.end(), [](std::string & s) { boost::trim(s); });
现在,编译器将有足够的知识使用默认参数