Date: Fri, 30 Oct 2020 19:12:43 -0700
Hi all,
I have a proposal to add "constexpr for" in addition to the existing
"constexpr if".
For example, I've written an C++17 "constexpr if" update to Nicolai M.
Josutti's print_tuple as follows below.
(http://cppstdlib.com/code/util/printtuple.hpp.html)
The code before the proposal:
template <std::size_t Idx, typename... Args>
std::ostream& print_tuple(std::ostream& os, const std::tuple<Args...>& t)
{
if constexpr (Idx < sizeof...(Args))
{
os << std::get<Idx>(t) << (Idx+1<sizeof...(Args) ? ","
: "");
print_tuple<Idx+1>(os, t);
}
return os;
}
template <typename... Args>
std::ostream& print_tuple(std::ostream& os, const std::tuple<Args...>& t)
{
print_tuple<0>(os, t);
return os;
}
The code after the "constexpr for" proposal:
template <typename... Args>
std::ostream& print_tuple(std::ostream& os, const std::tuple<Args...>& t)
{
for constexpr (std::size_t idx=0; idx<sizeof...(Args); ++idx)
{
os << std::get<idx>(t) << (idx+1<sizeof...(Args) ? ","
: "");
}
return os;
}
Conclusion:
1. The syntax in the new proposal is easier to understand.
2. The compiler implementation can hopefully build on foundations laid
down by constexpr if.
Thank you for reading and hope you find my proposal useful,
Gil
p.s.
1. Naturally, "constexpr while", "constepxr do while", etc... can also
be added to the proposal.
2. I'd be happy to follow with an initial proposal draft.
I have a proposal to add "constexpr for" in addition to the existing
"constexpr if".
For example, I've written an C++17 "constexpr if" update to Nicolai M.
Josutti's print_tuple as follows below.
(http://cppstdlib.com/code/util/printtuple.hpp.html)
The code before the proposal:
template <std::size_t Idx, typename... Args>
std::ostream& print_tuple(std::ostream& os, const std::tuple<Args...>& t)
{
if constexpr (Idx < sizeof...(Args))
{
os << std::get<Idx>(t) << (Idx+1<sizeof...(Args) ? ","
: "");
print_tuple<Idx+1>(os, t);
}
return os;
}
template <typename... Args>
std::ostream& print_tuple(std::ostream& os, const std::tuple<Args...>& t)
{
print_tuple<0>(os, t);
return os;
}
The code after the "constexpr for" proposal:
template <typename... Args>
std::ostream& print_tuple(std::ostream& os, const std::tuple<Args...>& t)
{
for constexpr (std::size_t idx=0; idx<sizeof...(Args); ++idx)
{
os << std::get<idx>(t) << (idx+1<sizeof...(Args) ? ","
: "");
}
return os;
}
Conclusion:
1. The syntax in the new proposal is easier to understand.
2. The compiler implementation can hopefully build on foundations laid
down by constexpr if.
Thank you for reading and hope you find my proposal useful,
Gil
p.s.
1. Naturally, "constexpr while", "constepxr do while", etc... can also
be added to the proposal.
2. I'd be happy to follow with an initial proposal draft.
Received on 2020-10-30 21:12:46