Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of vector elements at compile time (even if it is empty) using the Visual Studio compiler [duplicate]

Tags:

c++

visual-c++

Given a std::vector of elements of some type, how can I determine the size of the type of those elements at compile time using the Visual Studio compiler. Using sizeof on the first element is not an option as the vector could be empty.

For clang and gcc I can do something like this:

#include <vector>

template<typename T>
size_t size_of_vector_elements(std::vector<T> vector)
{
    return sizeof(T);
}


int square(int num)
{
    std::vector<unsigned> vector;
    return size_of_vector_elements(vector);
}

Using O2 this will be optimized at compile time to just return 4. MSVC however cannot optimize this.Is there a way to change this code to make it possible?

like image 737
Jerome Reinländer Avatar asked Apr 11 '19 07:04

Jerome Reinländer


People also ask

What is the size of an empty vector?

If the vector container is empty what will size() and empty() returns? Size will return 0 and empty will return 1 because if there is no element in the vector the size of that vector will be 0 and empty will be true so it will return 1.

How do you check if an element in a vector is empty?

vector::empty() The empty() function is used to check if the vector container is empty or not.

How do I get the size of a vector element in C++?

To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.

How do you return an empty vector?

Declare using std::cout and std::vector. Declare function with vector type return type which accepts vector as a variable.


2 Answers

In c++11 or later you can use decltype(vect)::value_type to get type of elements in std::vector

#include <iostream>
#include <vector>

int main()
{
    std::vector<double> vect;
    std::cout << sizeof(decltype(vect)::value_type); // gives you sizeof(double)
    return 0;
}
like image 71
Gor Asatryan Avatar answered Oct 03 '22 06:10

Gor Asatryan


Since you want MSVC to generate optimized code for the square function that is similar to what GCC generates, you will have to modify your code.

You can do away with the function template size_of_vector_elements and make use of the fact that sizeof does not evaluate its operand.

Then your modified square function simply becomes this:

int square(int num)
{
    std::vector<unsigned> vector;
    return sizeof(vector[0]);
}

The assembly that MSVC produces for this function at /O2 optimization is:

int square(int) PROC                                    ; square, COMDAT
        mov     eax, 4
        ret     0
int square(int) ENDP     

which is similar to what GCC produces at -O2 optimization.

square(int):
        mov     eax, 4
        ret

See godbolt demo.

like image 45
P.W Avatar answered Oct 03 '22 07:10

P.W