As already pointed out by @cpplearner in the comments above, the reason why this won't work is explained in detail here: Constructing std::function argument from lambda.
If your Sequence is already a template, there should be no reason to require the callable for your map
function to be passed in the form of an std::function
. At least, I seem unable to come up with a reason that could justify doing this. std::function
is generally not free to construct or call, and also can inhibit inlining. Best avoid it unless you really need the capability to store arbitrary callables for later use. Simply take a forwarding reference, e.g.:
template
auto map(F&& f) const;
You should be able to deduce the result type of whatever invoking f
on an element of your sequence ends up producing, e.g., via
decltype(f(std::declval()))
Furthermore, don't just return a raw pointer to a new Sequence
. Use an std::unique_ptr.
Putting it all together, your map
function could look something like this:
template
auto map(F&& f) const
{
using output_element_type = decltype(f(std::declval()));
auto sequence = std::make_unique>();
for (const T& element : *this)
sequence->push(f(element));
return sequence;
}