Goals
- A class with a function-typed member variable that can be used to choose a value from a range of values denoted by two iterators
- Should work in C++14, but if a (much) better solution is only possible in 17 or 20, I'd be interested nonetheless
Problem and Solution Sketch
Below is a sketch of the envisioned solution, with ???
denoting the choose-function's type, which I can't work out.
template<typename E>
class Producer {
??? choose_from; // A function It × It → E
...
public:
Producer(??? cf): choose_from{cf} {}
E next() {
// Get a bunch of values from internal state (omitted for brevity).
// Could also be another container, e.g. std::set.
std::vector<E> values = ...;
return choose_from(values.begin(), values.end());
}
}
Next up, a few example usage sketches of such a Producer
. A solution that only supports a subset of those would still be fine.
In combination with an existing function:
auto p = Producer<int>(std::max_element)`;
In combination with a lambda function:
auto p = Producer<int>([](auto begin, auto end)) { ... });
In combination with a custom free function:
template<typename E, typename It> E my_selector(It begin, It end) { ... } auto p = Producer<int>(my_selector);
Question
How do I get the code to work, i.e. what's the/a right type for member variable choose_from
?
Attempt & Thoughts
I've tried to use
std::function
to typechoose_from
, but since there is no abstract iterator type (AFAIK), I'm basically stuck atstd::function<E(IT?, IT?)>
.If the use of
std::vector
inProducer::next()
were leaked, I could fixchoose_from
's type to handlestd::vector<E>::iterator
s, but I'd much rather keep that internal detail hidden.