Order of parameter pack expansion

后端 未结 2 1483
眼角桃花
眼角桃花 2021-01-05 16:11

I have 2 functions to read binary file.

1st function reads sizeof(T) bytes from file:

template
T read() { ... some IO          


        
相关标签:
2条回答
  • 2021-01-05 16:22

    C++ does not specify the order in which a function's arguments are evaluated. If the expressions to a function all consume data from a stream, you can get behavior where objects are read in the wrong order.

    Braced initializer lists are evaluated from left to right, however, so you should get better results if you try something like:

    template<typename... Ts>
    std::tuple<Ts...> read_all() {
        return std::tuple<Ts...>{read<Ts>()...};
    }
    
    0 讨论(0)
  • 2021-01-05 16:44

    I would keep it a bit simpler and do this:

    uint32_t a;
    uint8_t b;
    std::tie(a, b) = read<std::tuple<uint32_t, uint8_t>>();
    

    This way there's only a single read() and you can even skip the tie() if you use the tuple (or struct) fields directly.

    0 讨论(0)
提交回复
热议问题