templated parameter packs
Unsolved
C++ Gurus
-
So I turned to templated programming to expand my c++ horizon.
I know, I already regret it :D
I have this very simple class, using templated parameter pack:
//Assumption/Usage: 1 Byte == 1 entry in m_versionParts template<typename... TArgs> explicit ApplicationVersion(TArgs... input){ //Check all arguments are an integer static_assert((std::conjunction_v<std::is_integral<TArgs>...>), "Only integer types are allowed."); QVector <uchar> versionParts; // Iterate through all inputs //Fold Expression, requieres C++17, calls processInteger for all arguments in the pack //Right Fold -> last argument given to the function is the least importan version part (..., versionParts.append(integerToByteVector(input))); //Left Fold //(versionParts.append(integerToByteVector(input)), ...); m_versionParts = versionParts; }
the helper function is here, if needed:
private: //Helper functions: template<typename T> [[nodiscard]] static QVector<uchar> integerToByteVector(T value) noexcept { static_assert(sizeof(T) > 0 && sizeof(T) <= sizeof(std::intmax_t), "Type size is not supported"); const auto typeSize = sizeof(T); QVector<uchar> bytes(typeSize, uchar{0}); for (uchar i = 0; i < typeSize; ++i) { bytes[i] = static_cast<uchar>((value >> (i * 8)) & 0xFF); } return bytes; }
the idea was to unravel the arguments list from back to front left and right fold do not seem to matter much/at all: see this modified example:
//Assumption/Usage: 1 Byte == 1 entry in m_versionParts template<typename... TArgs> explicit ApplicationVersion(TArgs... input){ qDebug() << Q_FUNC_INFO << "template<typename... TArgs> -> TArgs... input"; //Check all arguments are an integer static_assert((std::conjunction_v<std::is_integral<TArgs>...>), "Only integer types are allowed."); QVector <uchar> versionParts; QVector <uchar> versionParts2; // Iterthrough all inputs //Fold Expression, requieres C++17, calls processInteger for all arguments in the pack //Right Fold -> last argument given to the function is the least importan version part (versionParts.append(integerToByteVector(input)) , ...); (..., versionParts2.append(integerToByteVector(input))); qDebug() << Q_FUNC_INFO << versionParts << versionParts2; m_versionParts = versionParts; }
results in this console output:
ApplicationVersion::ApplicationVersion(TArgs...) [TArgs = <int, int, int, int>] QVector(1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0) QVector(1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0)with the same vector generated.
So I'm doing something wrong, or I have a wrong understanding. Any insight appreciated!