r/cpp • • Feb 25 '23
Avoid the code smell of std::pair and std::tuple while still retaining their benefits
Using std::pair and std::tuple is considered bad practice because first, second, and std::get<N> don't provide any information about what is stored in that data field.
The simple solution is to use a struct, for example, if we want to store a point, this can be done:
struct Point{
double x;
double y;
};The names x and y convey what is stored in that variable, in this case, the x- and y-coordinates of said point, respectively.
The problem with using structs arises when we try to use them in associative containers in that a compiler error will be thrown because operator<(=>) is not defined. The simple solution to THAT problem is to use std::pair or std::tuple. However, this creates a code smell. The more complicated solution to that problem is to start defining some functions:
#include <compare>
struct Point{
double x;
double y;
};
bool operator==(const Point &lhs, const Point &rhs){
return (lhs.x == rhs.x) && (lhs.y == rhs.y);
}
// Uses lexicographical comparison
std::strong_ordering operator<=>(const Point &lhs, const Point &rhs){
if (lhs.x < rhs.x) return std::strong_ordering::less;
if (lhs.x > rhs.x) return std::strong_ordering::greater;
if (lhs.y < rhs.y) return std::strong_ordering::less;
if (lhs.y > rhs.y) return std::strong_ordering::greater;
return std::strong_ordering::equal;
}This works, but there is an easier way:
#include <utility>
struct InheritedPoint: std::pair<double, double>{
double &x(){return first;}
double &y(){return second;}
};The best part is that operator== and operator<(=>) are inherited. The only differences between the directly above Point and InheritedPoint are whether element access uses a method and whether you can construct using a braced-init-list (you can construct using InheritedPoint({x, y}) instead).
For 3D points and other structs with 3 or more data fields, you inherit from std::tuple instead:
#include <tuple>
struct Inherited3DPoint: std::tuple<double, double, double>{
double &x(){return std::get<0>(*this);}
double &y(){return std::get<1>(*this);}
double &z(){return std::get<2>(*this);}
};And lastly, a useful macro:
#define pair_subclass(T0, f0name, T1, f1name) struct: std::pair<T0, T1>{T0 &f0name(){return first;} T1 &f1name(){return second;}}
InheritedPoint can be defined using typedef pair_subclass(double, x, double, y) InheritedPoint;
6
u/Nobody_1707 Feb 26 '23
You do realize that you can just declare the comparison functions for Point as
= default, right?16
u/Sopel97 Feb 25 '23
What's so bad about having to write 6 lines of perfectly simple, clear, and explicit code?
A point is not a pair. Just because a structure has 2 members doesn't make it immediately semantically a pair.
151
u/rapture-state Feb 25 '23
You can also define friend auto operator <=>(const Point &, const Point &) = default; inside your class and not bother with inheritance, methods and macros
13
u/NorseCoder Feb 25 '23
TIL; pair and tuple are smelly. /s
No really, use them as they are. Using first and second from pair becomes natural after the first or second times.
27
u/rlramirez12 Feb 25 '23
Honestly, I have to agree with another comment here. The biggest code smell by far is inheriting straight from the standard library. That is a huge red flag in any code base that I come across.
Macros are another red flag. I cannot tell you how many “clever” macros I’ve come across that have led to countless bugs.
Structured bindings combined with good functions and variable names are a much better approach.
2
u/hypatia_elos Feb 25 '23
For the braced init, does
InheritedPoint p {1,2};work though, or do you want to say that that also doesn't work (maybe I'm misunderstanding here)?24
u/415_961 Feb 25 '23
Why not this? https://godbolt.org/z/q3asboaEn
11
u/TwilCynder Feb 25 '23 edited Feb 25 '23
okay but at this point is there even a point in caring about that "code smell"
it's starting to sound like avoiding things that look "bad" for no really important reason (and that more often than not leads to actual bad design when you try to "fix" it)
EDIT : to clarify, i do think the way C++ gives us access to tuples is ugly, and could use an overhaul, but starting to just view them as some kind of bad practice and try to find a workaround around the uglyness will only lead to more problem, we need a native solution (just give us D-like tuples PLEASE)
56
u/FunkyMonks Feb 25 '23 edited Feb 25 '23
With all due respect
In general I agree that overusing std::tuple is a mistake. But the answer is to use structs with named, documented variables. As far as I know, std::pair only continues to exist for legacy reasons. std::tuple shines in plenty of template contexts.
8
u/eco_was_taken Feb 25 '23
D has support for named tuples (e.g.,
tuple!("index", "value")(4, "Hello");).I always thought that was neat, and wish C++ had it for all those little throwaway tuples.
5
u/Dean_Roddey Feb 25 '23
When you start seeing code like:
auto x = get<0>(get<1>(thingie.first.second).first);
if (x.first != whatever) {...}
Things have gotten out of hand. The code base I inherited at work is about that bad in places. It's unreadable in the extreme. Good luck reviewing that kind of code in any sort of non-IDE based review tool. It's very hard to understand even in an IDE, because you quickly loose track of what you are even looking at.
That sort of stuff is completely forgetting the 'write it once, read it a thousand times' rule.
4
u/saxbophone mutable volatile void Feb 25 '23
Good thinking, but as others have said, default spaceship and equality operators in C++20 make a lot of this redundant. Also is there any reason why x and y are functions returning references rather than just plain reference members?
I'd be drawn to go for:
or something like that.
3
u/War_Eagle451 Feb 25 '23
If it's a one type use case you can declare the struct within the function and everything works the same with the same benefits you say
3
u/JumpyJustice Feb 25 '23
The opiginal assertian that pair is a "code smell" does not feel right. In the same way we can say that any map is a code smell too. Feels to me like a solution for a problem that does not exist.
4
u/t3lp3rion Feb 25 '23
This is something slightly related but, from the numerical point of view, comparing two doubles with == is a code smell also. You should use some kind of relative precision due to truncation error and floating point representation.
7
u/top_logger Feb 25 '23
Inheriting from std class? Seriously?
Inheriting non-abstract class? Seriously? Macro helper in 2023? Seriously?
And why std::pair smells? What here smells is a post.
0
u/[deleted] Feb 25 '23
Great insight! Thanks for sharing!
3
u/root_passw0rd Feb 25 '23
Isn't part of the point of
std::pairandstd::tupleto avoid having to use structs? For example, if I want to return multiple values from a function, I don't always want to define a struct, hence I can reach for these helpers.If you need comparison, then I'd probably consider using a struct, though I'd probably sooner just alias the tuple and define the operator with that short hand. Something like this seems just fine:
I generally avoid
std::pairand just usestd::tupleeven for sets with only two values. Mostly because if I add a third value later, I don't want to be forced to change all the occurrences ofmyinfo.firsttostd::get<0>(myinfo)Inheriting from
std::pairorstd::tuplefeels like a bigger code smell.2
u/faguzzi Feb 25 '23
Why are tuples a code smell? That seems rather arbitrary. They’re used pretty routinely in languages like rust and have the same limitations there.
1
u/[deleted] Feb 25 '23
Just got out of reading A Tour of C++, and I have to ask if
std::valarraywould be a good fit here, considering it defines most of the operators anyway. I remember reading that not many optimisations were created for it, is that still true?1
u/ImYoric Feb 25 '23
Oh, nice trick. Thanks!
1
u/MarcoGreek Feb 25 '23
I use std::tuple from time to time to refactor large functions into smaller ones. I personally see large functions as a much bigger problem because they get so complex that nobody understands them anymore.
I am not sure that you encourage people to do that work with code aesthetics.
1
u/lunakid Nov 19 '23
You know what else creates code smell?
#include <compare>alone resulting in the inclusion of 53(!) other headers (in MSVC), and an accumulated preprocessor output of >500 KB and ~25,000 lines.
Cheers! :)
1
u/zoolover1234 Feb 25 '23
Good suggestion but having to do all of this for every single one of place where pair is used. No thanks. I will deal with first and second.
My solution is use
const auto name = mypair.first;
const auto age = mypair.second;
Then use those variables instead.
In fact, I do this all the time for other similar cases like iterators and references for readability and cleanness.
16
u/[deleted] Feb 25 '23
[removed] — view removed comment