从折叠表达式 return 值创建元组

Creating a tuple from a folding expression return values

我尝试使用 DecodeInternal 函数的返回值来创建这样的元组。

    std::tuple<Types...> Decode(const uint8_t *bufferBegin)
    {
        uint8_t *offset = (uint8_t *)bufferBegin;
        // (DecodeInternal<Types>(f, &offset), ...);
        return std::make_tuple<Types...>((DecodeInternal<Types>(&offset), ...));
    }

但是当我用这个模板参数编译时

decoder.Decode<int, float, bool, std::string, std::string>(encoder.GetBuffer().data());

我从编译器那里得到这个错误

In file included from ./borsh-cpp/src/main.cpp:4:
./borsh-cpp/src/BorshCpp.hpp: In instantiation of ‘std::tuple<_Tps ...> BorshDecoder::Decode(const uint8_t*) [with Types = {int, float, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >}; uint8_t = unsigned char]’:
./borsh-cpp/src/main.cpp:42:110:   required from here
./borsh-cpp/src/BorshCpp.hpp:244:35: error: invalid initialization of reference of type ‘int&&’ from expression of type ‘std::__cxx11::basic_string<char>’
  244 |   return std::make_tuple<Types...>((DecodeInternal<Types>(f, &offset), ...));
      |          ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/9/functional:54,
                 from ./borsh-cpp/src/BorshCpp.hpp:4,
                 from ./borsh-cpp/src/main.cpp:4:
/usr/include/c++/9/tuple:1470:27: note: in passing argument 1 of ‘constexpr std::tuple<typename std::__decay_and_strip<_Elements>::__type ...> std::make_tuple(_Elements&& ...) [with _Elements = {int, float, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >}]’
 1470 |     make_tuple(_Elements&&... __args)

(DecodeInternal<Types>(&offset), ...) 是一个 comma operator,其值等于最后一个表达式的结果。此外,您不需要为 make_tuple 显式指定模板参数,因此只需

return std::make_tuple(DecodeInternal<Types>(&offset)...);