Is it possible to have a lambda with a constexpr argument? And is it possible to make the following example work?
ForEach function provided below calls a given lambda 3 times with index 0, 1, 2:
template <class Func, std::size_t... index>
inline constexpr void ForEach(Func && f, std::index_sequence<index...>)
{
(f(index), ...);
}
template <class Func>
inline constexpr void ForEach(Func && f)
{
ForEach(f, std::make_index_sequence<3>());
}
so the following code
ForEach([](size_t index)
{
std::cout << index << ' ' << std::endl;
});
outputs 0, 1, 2.
But the following code that tries to print tuple elements requires index to be a constexpr:
auto t = std::make_tuple(1, 2.0, std::string("abc"));
ForEach([&t](size_t index)
{
std::cout << std::get<index>(t) << ' ' << std::endl;
});
and thus does not compile, see live example. Is it possible to make index constexpr somehow?
EDIT1: There is a working example where a lambda argument is used as a template argument:
void Set(Tuple& val, size_t index, Variant const& elem_v)
{
mp_with_index<std::tuple_size_v<Tuple>>(
index,
[&](auto I){
std::visit([&](auto const& alt){
if constexpr (std::is_assignable_v<
std::tuple_element_t<Tuple, I>,
decltype(alt)>)
{
std::get<I>(val) = alt;
} else {
throw /* something */;
}
}, elem_v);
});
}
why does this compile, but my sample code does not?
constexpr(not sure whetherC++20changes that).Iis astd::integral_constant<std::size_t, (something)>which has aconstexpr operator std::size_t()that returns that(something)