Amrane Abdelkader
Amrane Abdelkader

Reputation: 145

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.

Upvotes: 2

Views: 2009

Answers (3)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

There is another possible solution which illustrates how to solve the problem using SFINAE:

template<size_t N>
typename std::enable_if<N == 0>::type get(std::vector<std::size_t>& sizes) {}

template<size_t N, typename T, typename... Args>
typename std::enable_if<N != 0>::type get(std::vector<std::size_t>& sizes) {
    sizes.push_back(sizeof(T));
    get<N - 1, Args...>(sizes);
}

template<typename... Args>
const std::vector<std::size_t> get() {
    std::vector<std::size_t> sizes;
    get<sizeof...(Args), Args...>(sizes);
    return sizes;
}

Upvotes: 1

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

I would recommend using std::array for that:

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

Upvotes: 6

krzaq
krzaq

Reputation: 16421

You can just initialize the vector with the unpacked sizes:

template<typename... types>
std::vector<size_t> GetTypesSize()
{
    return { sizeof(types)... };
}

demo

Upvotes: 6

Related Questions