Search code examples
c++templatesvariadic

Getting the size of each type of the parameter pack?


After a long day of unsuccessful searching in the web for a practical solution to solve my problem, I decided to post my issue here, to clarify my goal I provided this simple code:

template<typename... types>
std::vector<SIZE_T> GetTypesSize()
{
    std::vector<SIZE_T> typesSizeContainer;
    typesSizeContainer.reserve(sizeof... (types)); 

    /*
     * What I want here is a mechanism to loop throw 
     * each element of the parameter pack to get its size 
     * then push it into typesSizeContainer.   
     * Something similar to :
     *
     *     for(auto& element : types...) {
     *         typesSizeContainer.push(sizeof(element));
     *     }
     * 
     */

    return std::move(typesSizeContainer);
}

When I call this function template in this code:

// platform x86
std::vector<SIZE_T> tempVactor;
tempVactor = GetTypesSize<char, short, int>(); 

The elements of the tempVactor should be { 1, 2, 4 }.

Any suggestion or solution is considerable.


Solution

  • I would recommend using std::array for that:

    template<typename... Types>
    constexpr auto GetTypesSize() {
        return std::array<std::size_t, sizeof...(Types)>{sizeof(Types)...};
    }