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

前端 未结 12 674
-上瘾入骨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:20

    You rarely see them because well-designed code usually doesn't need them- there are not to many cases in the wild where using an anonymous struct is superior to using a named one. Since all a tuple really represents is an anonymous struct, most coders in most situations just go with the real thing.

    Say we have a function "f" where a tuple return might make sense. As a general rule, such functions are usually complicated enough that they can fail.

    If "f" CAN fail, you need a status return- after all, you don't want callers to have to inspect every parameter to detect failure. "f" probably fits into the pattern:

    struct ReturnInts ( int y,z; }
    bool f(int x, ReturnInts& vals);
    
    int x = 0;
    ReturnInts vals;
    if(!f(x, vals)) {
        ..report error..
        ..error handling/return...
    }
    

    That isn't pretty, but look at how ugly the alternative is. Note that I still need a status value, but the code is no more readable and not shorter. It is probably slower too, since I incur the cost of 1 copy with the tuple.

    std::tuple f(int x);
    int x = 0;
    std::tuple result = f(x); // or "auto result = f(x)"
    if(!result.get<2>()) {
        ... report error, error handling ...
    }
    

    Another, significant downside is hidden in here- with "ReturnInts" I can add alter "f"'s return by modifying "ReturnInts" WITHOUT ALTERING "f"'s INTERFACE. The tuple solution does not offer that critical feature, which makes it the inferior answer for any library code.

提交回复
热议问题