<p>Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:</p>

<pre><code>find_if(serverNames.begin(), serverNames.end(), ContactServer());
</code></pre>

<p>Where ContactServer is a predicate function object.<br>
On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (<em>i.e.</em> the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.</p>

<p>What do you say?</p>

[{'answer_id': 27614, 'author': 'Magnus Hoff', 'author_id': 2971, 'author_profile': 'https://Stackoverflow.com/users/2971', 'pm_score': 2, 'selected': False, 'text': '<p>I think I would go for it.</p>\n\n<p>The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like "Find the first server I can contact", which makes perfect sense.</p>\n\n<p>You might want to rename <code>ContactServer</code> to indicate that it is a predicate; <code>CanContactServer</code>? (But then people would complain about hidden side effects. Hmm...)</p>\n'}, {'answer_id': 27619, 'author': 'Daren Thomas', 'author_id': 2260, 'author_profile': 'https://Stackoverflow.com/users/2260', 'pm_score': 0, 'selected': False, 'text': "<p>Isn't that what <code>find_if</code> is for?</p>\n\n<p>Note though, that it will find <em>all</em> the servers, if you iterate over the iterator - but you aren't going to do that (according to OP).</p>\n"}, {'answer_id': 27620, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 0, 'selected': False, 'text': "<blockquote>\n  <p>However, the same result will be returned regardless of which copy of the predicate is used (i.e. the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.</p>\n</blockquote>\n\n<p>So where's the problem? Function objects don't necessarily have to be stateful. It's actually best practice to use function objects instead of function pointers in such situations because compilers are better at inlining them. In your case, the instantiation and call of the function object may have no overhead at all since <code>find_if</code> is a function template and the compiler will generate an own version for your functor.</p>\n\n<p>On the other hand, using a function pointer would incur an indirection.</p>\n"}, {'answer_id': 39252, 'author': 'Xavier Nodet', 'author_id': 4177, 'author_profile': 'https://Stackoverflow.com/users/4177', 'pm_score': 0, 'selected': False, 'text': '<p>In the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2723.pdf" rel="nofollow noreferrer">upcoming version of the C++ standard</a>, I could not find any explicit restriction with respect to the fact that a predicate should always return the same value for the same input.  I looked into section 25 (paragraphs 7 to 10).</p>\n\n<p>Methods returning values that may change from one call to another, as in your case, should be volatile (from 7.1.6.1/11: "volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation").  </p>\n\n<p>Predicates "shall not apply any non-constant function through the dereferenced iterators" (paragraphs 7 and 8).  I take this to mean that they are not required to use non-volatile methods, and that your use-case is thus ok with respect to the standard.</p>\n\n<p>If the wording was "predicates should apply const functions..." or something like that, then I would have concluded that \'const volatile\' functions were not ok.  But this is not the case.  </p>\n'}, {'answer_id': 103138, 'author': 'Timmie Smith', 'author_id': 8405, 'author_profile': 'https://Stackoverflow.com/users/8405', 'pm_score': 0, 'selected': False, 'text': '<p>std::for_each might be a better candidate for this.</p>\n\n<p>1) After being copied in the same function object is used on each element and after all elements are processed a copy of the potentially updated function object is returned to the user.</p>\n\n<p>2) It would improve the readability of the call in my opinion as well.</p>\n\n<p>The function object and the for_each call would look something like:</p>\n\n<pre><code>\nstruct AttemptServerContact {\n  bool        server_contacted;\n  std::string active_server;    // name of server contacted\n\n  AttemptServerContact() : server_contacted(false) {}\n\n  void operator()(Server& s) {\n    if (!server_contacted) {\n      //attempt to contact s\n      //if successful, set server_contacted and active_server\n    }\n  }\n};\n\nAttemptServerContact func;\nfunc = std::for_each(serverNames.begin(), serverNames.end(), func);\n//func.server_contacted and func.active_server contain server information.\n</code></pre>\n'}, {'answer_id': 103164, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 0, 'selected': False, 'text': "<p>find_if appears to be the right choice here.  The predicate isn't stateful in this situation.</p>\n"}, {'answer_id': 113129, 'author': 'wilhelmtell', 'author_id': 456, 'author_profile': 'https://Stackoverflow.com/users/456', 'pm_score': 2, 'selected': False, 'text': '<p>This is exactly what the STL algorithms are for.  This is not an abuse at all.  Furthermore, it is very readable.  Redirect to null anyone who tells you otherwise.</p>\n'}, {'answer_id': 10757848, 'author': 'Luc Touraille', 'author_id': 20984, 'author_profile': 'https://Stackoverflow.com/users/20984', 'pm_score': 2, 'selected': False, 'text': "<p>In my opinion, this use of <code>std::find_if</code> is a bit misleading. When I read this piece of code, I don't expect any side effects to occur, I just expect a server name to be found. The fact that the result of <code>find_if</code> is discarded would also make me wonder if the code is really correct. Perhaps another name for the predicate would make the intent clearer, but I think the problem is more fundamental.</p>\n\n<p>For most people, <code>find_if</code> is a <strong>querying</strong> algorithm, not a <strong>modifying</strong> algorithm. Even though you are not actually modifying the values iterated upon, you are modifying the global state of your application (in this case, you are even possibly modifying the state of distant servers).</p>\n\n<p>In such a case, I would probably stick with a manual loop, especially now that C++11 introduced range-based for loops:</p>\n\n<pre><code>for (std::string const &amp; name : serverNames)\n{\n    if (ContactServer(name)) break;\n}\n</code></pre>\n\n<p>Another solution would be to encapsulate this in a function with a name conveying more clearly the intent, such as <code>apply_until</code> or something like that:</p>\n\n<pre><code>template &lt;typename InputIterator, typename Function&gt;\nvoid apply_until(InputIterator first, InputIterator last, Function f)\n{\n    std::find_if(first, last, f);\n    // or\n    // while (first != last)\n    // {\n    //     if (f(*first)) break;\n    //\n    //     ++first;\n    // }\n}\n}\n</code></pre>\n\n<p>But perhaps I'm being over-puristic :)!</p>\n"}]
['https://Stackoverflow.com/questions/27607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2150/']