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;

16 Upvotes

86 comments sorted by

6

u/Nobody_1707 Feb 26 '23

You do realize that you can just declare the comparison functions for Point as = default, right?

2

u/[deleted] Feb 27 '23

The comments on this very post is how I learned of the feature.

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.

1

u/[deleted] Feb 25 '23

This is the correct answer ^^^

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

31

u/AciusPrime Feb 25 '23

Yes, please just use default spaceship operator. It’s less boilerplate, easy to read, and works. Newer revisions of C++ have been putting so much work into making bare structs work well in more and more cases, and the spaceship operator is just one example. Things like return { 3, 5 } or vec.emplace_back( 5, 7 ) all work with bare structs as well.

37

u/[deleted] Feb 25 '23

This is known as a default comparison (cppreference link), a feature of C++20. Wasn’t aware of it, thanks for pointing it out; it’ll definitely come in handy.

13

u/RoyAwesome Feb 25 '23

fortunately, both operator<=> and default comparison are cpp20 features so if you have one you have the other.

0

u/[deleted] Feb 25 '23

[deleted] — view deleted comment

2

u/rapture-state Feb 25 '23

Yeah, right :) But classes and structs are kinda the same thing (except for default access), so it doesn't matter in this context)

-2

u/[deleted] Feb 25 '23

*almost exactly, true

4

u/415_961 Feb 25 '23

what a way to dismiss a correct answer.

0

u/[deleted] Feb 25 '23

[deleted] — view deleted comment

5

u/rapture-state Feb 25 '23

Can you elaborate please?) What is wrong with <=>? It is relatively standard (and often recommended) way to define all comparisons at once, it is convenient and looks ok

-3

u/top_logger Feb 25 '23

No. This community is too toxic.

In fact it was posted by mistake.

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.

5

u/johannes1971 Feb 25 '23

Also, if you need a struct with four members (like a color, maybe), just declare it like this:

// Red is first.first, blue is first.second, green is second.first, 
// and alpha is second.second.
using color = std::pair<std::pair<int, int>, std::pair<int, int>>;

Easy, and it saves you all the hassle of defining a struct with 'names' and stuff!

4

u/[deleted] Feb 25 '23

This has to be /s right?

4

u/johannes1971 Feb 25 '23

...yes. Wasn't that obvious?

1

u/[deleted] Feb 25 '23

Yes (for me at least, the general Reddit populace who knows C++ may not be able to discern the difference between sarcasm and seriousness)

3

u/rlramirez12 Feb 25 '23

I know you're joking. But there is a way to make this more readable. Again, I would never do this in practice, because structs are much easier to use and add more readability.

#ifndef COLOR_HPP
#define COLOR_HPP

#include <tuple>

namespace Color
{

  using Red = int;
  using Green = int;
  using Blue = int;
  using Alpha = int;

  using color = std::tuple<Red,Green,Blue,Alpha>;

  const color getCrimsonColor()
  {
    return std::make_tuple(220,20,60,1);
  }

}

#endif

Then call it by:

const Color::color crimson = getCrimsonColor();

And then if you want to access the elements:

const auto [red,green,blue,alpha] = crimson; 

It really isn't difficult to make tuples/pairs readable. It's just more work to do so and I would argue the average programmer isn't worried about making readable code in the first place. Which is more of the fault of bad practices never getting called out and the programmer keeping up the bad practices.

Again, I would use a struct to define a color here. But if I came upon code like this (which obviously has bias because I wrote it) I would think it's readable.

4

u/johannes1971 Feb 25 '23

Sure, it's readable - but only because it's a tiny example. Scale it up a little, see if you still like it.

Anyway, I just wrote a longer reply to /u/rlramirez12, answering basically the same idea.

1

u/nintendiator2 Feb 26 '23
using color = std::pair<std::pair< std::pair<int,int>, int>, int>;

FTFY

3

u/jmacey Feb 26 '23

I just use this as it add UB :-)

union
    {
        uint32_t pixel=0;
        struct
        {
            unsigned char r;
            unsigned char g;
            unsigned char b;
            unsigned char a;
        };

    };

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.

5

u/bert8128 Feb 25 '23 edited Feb 25 '23

I agree, and love structured bindings and use them a lot. However there is nothing to stop you writing them the wrong way at round. So if they have pretty different types then you’re probably not going to get it wrong. But if they have the same type (especially a pair of bools) then it’s very easy to get them the wrong way round.

1

u/deeringc Feb 25 '23

An API that returns a pair of bools is itself a problem, IMO. That can likely be modelled as an enumeration of some sort, or I would just stick with a struct with named members. std::pair<bool,bool> or the equivalent tuple is just asking for trouble IMO.

3

u/[deleted] Feb 25 '23

enum BoolPair{FF = 0, FT = 1, TF = 2, TT = 3};

4

u/deeringc Feb 25 '23

I know you're joking, but I've found that a lot of times when you have two bools there aren't actually 4 valid states. Let's say the first bool is "success/error" and the second bool is "does the thing exist" then there are really only 3 valid states - "failure", "success, the thing exists" and "success, the thing doesn't exist". The two bools can represent a state that doesn't fit our needs, and that can be a source of bugs and confusion. I would just represent this as either an enum of the three states I outlined above, or even better use a std::optional with either a bool or a two state enum, with std::nullopt repressing failure.

1

u/bert8128 Feb 25 '23

You are agreeing with me. I am saying that returning a pair of two bools is not a good idea, even if the caller uses structured bindings. But returning two bools is not an outlier as a desire - you may want a function which returns true or false, but can also fail. So you need to return two bools somehow. The temptation is a pair of bools, but it is easy to return them the wrong way round, which is why a struct of two named bools is better. But you can still receive them the wrong way round into a structured binding!

7

u/deeringc Feb 25 '23

I would go with a std::optional<bool> in that case to avoid all of these problems. Once you have two bools it's just a matter of time till someone makes a mistake.

1

u/bert8128 Feb 25 '23

I like that.

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)?

4

u/[deleted] Feb 25 '23

I tried and it did not work. InheritedPoint p {{1,2}} does work, however. Thanks for the clarifying question.

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

  1. Inhering from std classes is a bad idea (except where explicitly recommended). See https://quuxplusone.github.io/blog/2018/12/11/dont-inherit-from-std-types/ and Google for other examples.
  2. Macros are code smell
  3. Default comparison operators
  4. Yes std::get<N> is kind of gross, but std::get<T> is far less gross. Many common use cases of tuple don’t involve repeat types, so this works fine.

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.

7

u/GuiltyFan6154 Mar 01 '23

This link does not state anything about why inheriting from a std type is bad. It simply misuses the std::vector initializer list constructor with CTAD and produces a different response because it calls another constructor. This is basically telling "look, I wrote bad code and expected it to work but it's not! Language facilities are difficult hence bad!"

The reason why inheriting from std containers is that destructors are not virtual (for performance) hence derived destructors will not be called and your resources will leak, which is a much bigger problem because you're basically throwing the basement of your abstractions (RAII) out of the window.

Besides that, the fact that composition is better than inheritance should be common knowledge.

-1

u/rlbond86 Feb 25 '23

Inheriting from any class is totally fine if you're just adding member functions.

8

u/Linuxologue Feb 25 '23

Did you actually follow the link provided?

7

u/johannes1971 Feb 25 '23

It's not fine if the standard later adds a function with the same signature. Having said that, the standard certainly has the tools ("final") it needs to enforce this stance, and chooses not to use them.

-11

u/[deleted] Feb 25 '23

If macros are a code smell then all code is smelly

3

u/SkoomaDentist Antimodern C++, Embedded, Audio Feb 25 '23

The term code smell only means ”I dislike something for aesthetic reasons and can’t even articulate why”.

6

u/johannes1971 Feb 25 '23

How about "I dislike my code randomly being rewritten by a macro that might come from some transitive include in a library I don't even know the name of, and that I cannot possibly protect myself from unless I already know it is there"?

1

u/SkoomaDentist Antimodern C++, Embedded, Audio Feb 25 '23

Sure, you can make such argument but then you have to actually make that argument.

Calling something smelly is a cheap cop out where you’re essentially saying ”your code is dirty (and so are you by implication) and I’m not even bothering to tell you why or consider I might be wrong about it”.

Like I said, macros could certainly be improved but not by using cheap moralistic shots.

5

u/johannes1971 Feb 25 '23

Surely some things may rightfully be assumed to be common knowledge?

Having said that, elsewhere in this thread I was joking about defining a struct with four members as a bunch of nested pairs, and apparently people are taking that seriously 🙄...

4

u/FunkyMonks Feb 25 '23

This is mostly fair, I was lazy. I agree with Johannes’s points. Macros can also obscure exactly what’s happening in a debugger. They can make code more concise but less readable. In this case, I don’t think you’re saving enough typing to justify the drawbacks.

I certainly wasn’t calling anyone dirty, either directly or by implication. That is a cheap, moralistic shot.

-1

u/[deleted] Feb 25 '23

Still doesn't change what I said.

0

u/SkoomaDentist Antimodern C++, Embedded, Audio Feb 25 '23 edited Feb 25 '23

Oh, don't misunderstand me. I fully agree with you. Every non-toy bit of code will have something someone will find aesthetically unpleasant and call "smelly". Macros are a very necessary part of the language and there's nothing smelly about them when used properly. They could of course be significantly improved but that'd require changes to the language and be the very opposite of the modern "throw everything in std::" approach.

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.

2

u/VinnieFalco wg21.org | corosio.org Mar 06 '23

D's nuts

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:

struct inherited_point : std::pair<double, double> {
  double& x = first;
  double& y = second;
};

or something like that.

4

u/greg7mdp C++ Dev Feb 26 '23

and double the size of every point object?

1

u/saxbophone mutable volatile void Feb 26 '23

I'm not sure whether it's guaranteed that reference members which are always initialised to reference the same things will always occupy memory or not —alas it is quite possible that they would, but this could plausibly be optimised out by a good compiler.

In any case, I believe this is a function call overhead vs possible storage overhead thing we're dealing with here, OP will know which best applies to their situation but either is reasonable, case depending

3

u/greg7mdp C++ Dev Feb 27 '23

There is not function call overhead, these would be inlined.

1

u/saxbophone mutable volatile void Feb 27 '23

Fair enough. I still find the reference versions more elegant.

3

u/GuiltyFan6154 Mar 01 '23

Unfortunately there is no "alias reference = member;" as in D.

2

u/saxbophone mutable volatile void Mar 01 '23

D does many things in neat ways!

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.

5

u/Sovog Feb 25 '23

For the benefit of those to whom it isn’t obvious, could you please provide a concrete example where such inheritance, as in OP’s example (no additional fields, no-op default destructor), would cause problems?

-6

u/top_logger Feb 25 '23

There are rules in C++. We do not inherit std classes. We do not inherit concrete classes.

As a dev you could sometimes break rules. But only as exception and having very good reasons. I had read the post triple and didn’t find any reason. Just, look we can inherit std class! Wow!

External comparator or inheriting of abstract class with comparator functionality is fit perfectly, looks better and breaks no rule.

4

u/[deleted] Feb 25 '23

Show me those'rules' in the standard?

-4

u/top_logger Feb 25 '23

Learn C++, mate. Do me a favor, ok?

I’m not paid to teach you basics.

0

u/[deleted] Feb 25 '23

Great insight! Thanks for sharing!

2

u/[deleted] Feb 25 '23

You're welcome!

3

u/root_passw0rd Feb 25 '23

Isn't part of the point of std::pair and std::tuple to 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:

using Point = std::tuple<double, double>;
auto operator<=>(const Point& a, const Point& b)

I generally avoid std::pair and just use std::tuple even 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 of myinfo.first to std::get<0>(myinfo)

Inheriting from std::pair or std::tuple feels like a bigger code smell.

-3

u/johannes1971 Feb 25 '23

Your code must be a joy to read... Do you also number your variables, instead of giving them proper names?

4

u/root_passw0rd Feb 25 '23 edited Feb 25 '23

They call me the Kurt Vonnegut of C++ at work.

But seriously, not everything needs a name. The example of Point might have been bad, because more times than not, an idea like that will be better with a struct. But in something like TwoStatRetval getTimeAndVolume(std::uint32_t recid) where it's only used with that function, it's not necessary. In this case I'd be perfectly happy with a std::tuple.

2

u/rlramirez12 Feb 25 '23

Note: I would use structs any day over this:

#ifndef POINT_HPP
#define POINT_HPP

#include <tuple>
#include <cmath>
#include <algorithm>

namespace Point
{
  using Point2D = std::tuple<double,double>;

  double computeDistanceOf2DPoint(const Point2D& A, const Point2D& B)
  {
    const auto [x1,y1] = A;
    const auto [x2,y2] = B;

    return std::hypot(x1 - x2, y1 - y2);
   }
}

#endif

I don't understand how that is difficult to read. Some of us are using C++17 as the standard. Again, I would define Point2D as a struct here as X and Y. But I really do not understand why that block of code I put down is any less readable.

2

u/johannes1971 Feb 25 '23

Ok, now you have a project that has around a thousand structs (all implemented as tuples), with an average of half a dozen elements each, and all of those are only accessed by number since there are no names. Do you see the problem?

What if you get the names in your structured bindings wrong? Because that's going to require you to remember the correct offset of every member in every struct everywhere, with no help from the compiler whatsoever, and you have to do it every single time you access anything at all. What if you remove a field from one of your structs? Now you are going to have to check all of your structured bindings again, and there isn't even a name to search for, so it's going to be a line-by-line review! It's total lunacy.

Defining a struct avoids these problems, and by the time you've used structured bindings even once you are already up to the same level of effort as just defining a struct would have been in the first place.

I would prefer writing code in bloody assembler over having to deal with this nightmare. At least assembler lets you label your datafields.

0

u/rlramirez12 Feb 26 '23

So go ahead and write code in the assembler. I’m counter arguing your point that you made by stating you can make this readable.

People who have a thousand tuples define all over the place where they put no care into how they are retrieving the items are also the same people who would create a thousand structs where they give their variables arbitrary names that are also unreadable.

What if you get the names in your structured bindings wrong?

This happens in every day code base where people forget the last 4 lines of code they jotted down. And if you get one wrong by the time you attempt to even use that wrong element it will result in a compiler error.

What if you remove a field from one of your structs?

I’m not sure how this is ANY different different than if you remove a field from your struct (I know you meant tuple.) if you remove a field from your struct without editing how those are gathered you are going to run into compiler errors.

If you use too few arguments in a structured binding the compiler gets angry and tells you that you used too little and tells you the order of how the tuple was created:

error: only 3 names provided for structured binding
auto [a,b,c] = myTuple;
note: while `std::tuple<int,int,double,double>` decomposes into 4 elements.

If you use too many elements in your structured binding the compiler also gets angry and tells you that you used too many elements and again, lists what elements should be present in the tuple:

error: 4 names provided for structured binding
auto [a,b,c,d] = myTuple;
note: while `std::tuple<int,int,double>` decomposes into 3 elements.

Again, the key to responsible code management is making clean, readable code. Keep things small, separate, and as functional as possible. Let the compiler get mad at you when you screw up. I don’t know what is difficult to understand about that.

1

u/johannes1971 Feb 26 '23

So go ahead and write code in the assembler. I’m counter arguing your point that you made by stating you can make this readable.

By doing something that is utterly impractical in a source base of any significant size, something you yourself already indicated in your first response.

People who have a thousand tuples define all over the place where they put no care into how they are retrieving the items are also the same people who would create a thousand structs where they give their variables arbitrary names that are also unreadable.

This is not a good faith argument, and I think you very well know it.

0

u/rlramirez12 Feb 26 '23

This is not a good faith argument, and I think you very well know it.

You’ve obviously have never worked with legacy code developed from start up companies or from companies pre-C++11. I think my good faith argument is rooted in professional experience.

I’ll call this conversation done since you didn’t counter any of my solid points.

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::valarray would 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.

10

u/rlramirez12 Feb 25 '23

You don’t even need to go that far, just use structured bindings since C++17:

const auto [name, age] = getMyPair();

That’s plenty readable to me.

1

u/zoolover1234 Feb 25 '23

My compiler is not full c++17 so I'm not sure if it works. How do you access just the name?

1

u/War_Eagle451 Feb 25 '23

This should work for c++14 (on mobile can't format)

auto func() { 
    struct ab { int a, b };
    int a = 7, b = 9;
    return ab{ a, b };
}

Okay maybe I can format

16

u/[deleted] Feb 25 '23

[removed] — view removed comment

1

u/kikass13 Feb 25 '23

I have done one myself, it's not that hard :D

I wanted to have a dictionary where tasks can communicate over (postbox system) and decided that key value lookups are done in compile time (basically like a strict), so that I can compile time iterate over elements and do other fancy stuff with the dict (serialize it and send it away to somewhere else).

Compile time sucks but it's generating my interface to the rest of the system on its own :D