I have the function GetThing
as follows:
auto GetThing(size_t index, auto&& l1)
{
return l1;
}
auto GetThing(size_t index, auto&& l1, auto&&... rest)
{
if (index == 0)
return l1;
return GetThing(index - 1, rest...);
}
I want it to be able to work with different lambdas too while being able to handle other types (meaning non-lambdas, non functions, like int
, and ...) , such as
std::cout << GetThing(1, 2, 3, 4); //works, return 3
std::cout << GetThing(1, [] {return 0; },
[] {return 1; }, [] {return 2; },
[] {return 3; } )(); //nope
But the problem here being the lambdas are different type, therefore the recursive function will deduced to incompatible return type, so I seems to have to use std::function
like this, but it's ugly.
std::cout << GetThing(1, std::function{ [] {return 0; } }, std::function{ [] {return 1; } }, std::function{ [] {return 2; } }, std::function{ [] {return 3; } })();//works
Any possible way to get around this, for example if there is an overloaded operator()
then it automatically enforce the type to be std::function
?
EDIT: I am aware of capture-less lambdas can be converted to a function pointer, but how to deduce it that way without std::decay
in the template? Because I still want to to be handle other types as references
EDIT2: I receive a few answers utilizing std::variant
, and am thinking of that, besides lambda, the parameter types shall be the same, eg. std::variant<int, int, int>
. It maybe possible to add overload to GetThing
, such that whenstd::variant
is holding the same types, it return the thing of that type, otherwise (which is the case of receiving lambdas), returns a std::function