The variable 'comp' with type <some anonymous lambda class> can be made static, much like any other local variable, that is, the same variable pointing to the same memory address each time this function is run) .
However, be careful when using closures, which will lead to subtle errors (passing by value) or errors at runtime (pass-by-reference), since closure objects are also initialized only once:
bool const custom_binary_search(std::vector<int> const& search_me, int search_value, int max) { static auto comp_only_initialized_the_first_time = [max](int const a, int const b) { return a < b && b < max; }; auto max2 = max; static auto comp_error_after_first_time = [&max2](int const a, int const b) { return a < b && b < max2; }; bool incorrectAfterFirstCall = std::binary_search(std::begin(search_me), std::end(search_me), search_value, comp_only_initialized_the_first_time); bool errorAfterFirstCall = std::binary_search(std::begin(search_me), std::end(search_me), search_value, comp_error_after_first_time); return false;
Note that the "max" parameter is here to introduce a variable that you might want to capture in your comparator, and the functionality that this "custom_binary_search" implements is probably not very useful.
source share