Note that there are some explanatory texts on larger screens.

plurals
  1. POstd::for_each ignoring default function argument
    primarykey
    data
    text
    <p>I stumbled on a strange compilation problem. I want to process a list of strings, using <code>std::for_each</code>. The following simplified code illustrates the problem :</p> <pre><code># include &lt;list&gt; # include &lt;string&gt; # include &lt;algorithm&gt; using namespace std ; void f(wstring &amp; str) { // process str here } void g(wstring &amp; str, int dummy = 0) { // process str here, same as f, just added a second default dummy argument } int main(int, char*[]) { list&lt;wstring&gt; text ; text.push_back(L"foo") ; text.push_back(L"bar") ; for_each(text.begin(), text.end(), f) ; // OK, fine :) for_each(text.begin(), text.end(), g) ; // Compilation error, complains about // g taking 2 arguments, but called within std::for_each // with only one argument. // ... return 0 ; } </code></pre> <p>I tested using MinGW 4.5.2 and MSVC10, both reported the same error message. Originally, I wanted to use <code>boost::algorithm::trim</code> as a processing function passed to <code>std::for_each</code>, but I found that it takes two arguments, the first being mandatory (the string to process) and the second one is optional (a locale providing a definition for space chars).</p> <p>Is there any way to keep things clean when using <code>std::for_each</code>(and other standard algorithms) when having functions or methods with default arguments ? I found a way to make it work, but it is no more clear and easily understandable, so a <code>for</code> loop begins to seem easier ...</p> <pre><code># include &lt;list&gt; # include &lt;string&gt; # include &lt;algorithm&gt; # include &lt;boost/bind.hpp&gt; # include &lt;boost/algorithm/string.hpp&gt; using namespace std ; using namespace boost ; // ... somewhere inside main list&lt;wstring&gt; text ; for_each(text.begin(), text.end(), bind(algorithm::trim&lt;wstring&gt;, _1, locale()) ; // One must deal with default arguments ... // for_each(text.begin(), text.end(), algorithm::trim&lt;wstring&gt;) would be a real pleasure </code></pre> <p>Thanks for any help !</p> <p><em>Note</em> : I just started learning English, sorry for mistakes :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload