Why is the use of tuples in C++ not more common?

前端 未结 12 549
-上瘾入骨i
-上瘾入骨i 2021-01-29 23:48

Why does nobody seem to use tuples in C++, either the Boost Tuple Library or the standard library for TR1? I have read a lot of C++ code, and very rarely do I see the use of tup

12条回答
  •  失恋的感觉
    2021-01-30 00:17

    But what if you want to rotate three values?

    swap(a,b);
    swap(b,c);  // I knew those permutation theory lectures would come in handy.
    

    OK, so with 4 etc values, eventually the n-tuple becomes less code than n-1 swaps. And with default swap this does 6 assignments instead of the 4 you'd have if you implemented a three-cycle template yourself, although I'd hope the compiler would solve that for simple types.

    You can come up with scenarios where swaps are unwieldy or inappropriate, for example:

    tie(a,b,c) = make_tuple(b*c,a*c,a*b);
    

    is a bit awkward to unpack.

    Point is, though, there are known ways of dealing with the most common situations that tuples are good for, and hence no great urgency to take up tuples. If nothing else, I'm not confident that:

    tie(a,b,c) = make_tuple(b,c,a);
    

    doesn't do 6 copies, making it utterly unsuitable for some types (collections being the most obvious). Feel free to persuade me that tuples are a good idea for "large" types, by saying this ain't so :-)

    For returning multiple values, tuples are perfect if the values are of incompatible types, but some folks don't like them if it's possible for the caller to get them in the wrong order. Some folks don't like multiple return values at all, and don't want to encourage their use by making them easier. Some folks just prefer named structures for in and out parameters, and probably couldn't be persuaded with a baseball bat to use tuples. No accounting for taste.

提交回复
热议问题