- std::apply(printImpl<int, int, double>, tp);
+ std::apply(printImpl<Args...>, tp);https://godbolt.org/z/vfcd5YoWE
And the function that the author arrives at similarly supports other types than std::tuple:
But now I see the issue and it's improved. So the version:
template <typename... Args> void printTupleApplyFn(const std::tuple<Args...>& tp) { std::cout << "("; std::apply(printImpl<Args...>, tp); // << std::cout << ")"; }
is fine and probably the easiest
template <template <typename...> typename Wrapper, typename... Args>
void printTupleApplyFn(const Wrapper<Args...>& tp) {
// no further changesYour suggestion fails for e.g. std::array, which is also tuple-like:
https://godbolt.org/z/qYhdfjrY3
User-defined types can also specialize the required templates to opt-in to tuple-like behavior. In fact, doing so enables structured binding support, so it's not unlikely to see something like
Vec3 getCoords();
auto [x, y, z] = getCoords();
(where Vec3 specializes std::tuple_element etc.), and you wouldn't want your tuple printing code to error out when given a Vec3 either. In fact, Vec3 might not even be a template in the first place!One of the challenges with this sort of unmotivated code (unmotivated in a literal sense, not a derogatory sense -- we don't know what's motivating it) is that it's very hard to know how general a solution to design. I love the C++ template universe when things "just work," but it's very easy to get into a cycle where just a /bit/ more complexity gets you a /bit/ more generality -- only to realize that after beautifully polishing that modular code, you only use it in one or two contexts.
std::apply is a good example of putting that generality and complexity into the standard library; if a caller can then use that directly, even with loss of generality, that's usually my preference. If nothing else, it means folks encountering the caller will have fewer layers to understand, and many fewer non-standard layers.
Is there some good reason why tuple_size couldn't have been made to work on const tuples?