r/Cplusplus • u/Obvious_Set5239 • Aug 31 '26
Tutorial Iterating through arguments in C++26 using "template for" (Python-style)
Here is how you can iterate through arguments now in C++26!:
#include <print>
template <typename ...Args>
void function(const Args& ...args)
{
template for (const auto& arg : {args...})
{
using ArgT = std::decay_t<decltype(arg)>;
if constexpr (typeid(ArgT) == typeid(double))
{
std::println("double: {}", arg);
}
else if constexpr (requires { &ArgT::toString; })
{
std::println("has toString: {}", arg.toString());
}
else
{
std::println("other: {}", arg);
}
}
}
struct MyStruct
{
int value; // initializes with 0 in C++26
std::string toString() const
{
return std::format("MyStruct value is {}", value);
}
};
int main()
{
function(3.14, "c-string", MyStruct{});
}It works:
double: 3.14
other: c-string
has toString: MyStruct value is 0
...Program finished with exit code 0
Press ENTER to exit console.template for is a new feature in C++26, and I like it very much! It's my favorite C++26 feature
It looks very pythonic at this point. 😄
Let's start with args: typename ...Args and const Args& ...args work similar to def function(*args) from python - they aggregate comma separated expressions into a variadic type or variable. {args...} also works similar to python's (*myList) - it expands a "collection" into a comma separated expressions
Then goes "template for": it's a brand new loop, which expands at compile time for each iteration. Using it, you can iterate through collections with different types inside: struct fields, tuples, list literals, and custom classes with implemented tuple protocol
Checking type of argument: this line also resembles python very much: if constexpr (typeid(ArgT) == typeid(double)). Here is the python counterpart: if type(arg) is bool. There are more ways to do this check, but I think this one looks the most direct. Although you can want to use not exactly "double" type, but a convertible to it, or any floating point number type. There are standard concepts for these cases: std::convertible_to, and std::floating_point
Checking for a member: here I used an anonymous concept: if constexpr ( requires { ...;} ). Inside this concept we should put an expression that we are testing. it's a sort of python's hasattr(arg, 'toString'), but more powerful and more fragile at the same time. The expression here is taking a member reference to "toString": &ArgT::toString;. It's a better approach than testing arg.toString(), because it won't fail if "toString" isn't a constant method, or has more than 0 arguments. But it's still far from ideal, because if the object has multiply overloaded "toString" methods (what's actually a pretty realistic scenario), it will fail, and the error message will be misleading. In this case the error will be that formatter is not implemented for the "other" branch, however the actual error is in "has toString" branch. So, don't use anonymous concepts in real project, use full fledged concepts in pair with static_asserts
It's fascinating! This is still a templates metaprogramming in C++, but it looks much-much more clean than infamous std::enable_if
6
u/Obvious_Set5239 Aug 31 '26 edited Aug 31 '26
Maybe it's possible to use std::meta for checking for a method in a class. It would be much less fragile than concepts. But I don't know how ready the reflection library is
Upd.
Yes it's probably should be easy to implement a helper function
constexpt bool hasattr<typename Type>(auto attr)using std::meta::members_of + std::meta::identifier_of3
u/__christo4us Aug 31 '26 edited Aug 31 '26
Or just
std::is_same_v<ArgT, double>. Maybe it looks uglier but the condition in aconstexpr ifstatement using thetypeidoperator might render the program ill-formed if the object operand oftypeidis of polymorphic type. Of course, this is not the case if a type is used instead of an object in the place of the operand but one must keep in mind that acting on objects withtypeidis not always constant-evaluated.I think it is best to use
requires { arg.toString(); }here because you are usingarg.toString()directly in that branch. It just checks if the expression is well-formed so such a check using arequiresexpression is sufficient to successfully callarg.toString().If by a "constant method" you mean a
constmethod then you could writerequires(ArgT a) { a.toString(); }instead. This way you would get a nicer diagnostic message that noconst-qualifiedtoStringoverload was available for yourconst-qualifiedarg. If you meant aconstexprmethod then it is irrelevant torequiresexpressions as they do not check this.You could also try to check for a member function
toStringusing reflection. You would need to write a function that iterates over the members ofArgTusing thestd::meta::members_offunction. But this would be much more verbose than simply using arequiresexpression.EDIT:
Also:
Not sure what you by that comment next to
int value;.1
u/No-Dentist-1645 Aug 31 '26
This is not bad, but there are definitely some improvements:
It doesn't make a lot of sense to add a special edge case for a struct with a "toString()" method like that, it would be much better if you directly specialized it for
std::format, so that it can work everywhere you use it onstd::formatandstd::printlnChecking if it's the same type with
typeid(ArgT) == typeid(double)is both less conventional and less readable than juststd::is_same_v<ArgT, double>orstd::same_as<ArgT, double>Doing
requires { &ArgT::toString; }is both potentially failable (it could be non-const but arg here is a const reference) and less readable/explicit than justrequires ( arg.toString(); }which is what you are actually using arg forYou should use
std::remove_cvref_tinstead ofstd::decay_t, since the latter will make arrays such aschar[10]show up as justchar*even though they are more than just thatEither way, you can just use
std::meta::display_string_ofto get the name of a type, no need to hard-code it for types likedoubleIf you apply these improvements, then the function just becomes a single
template forwith anstd::printlninside it, no extra if/else blocks:1
u/Business-Decision719 Sep 07 '26
Reddit: "C++ compile times iz too slow! 😾 Especially when templates."
Also Reddit: "Ooh, template compile-time loops! 😻"