给定std::vector某种类型的元素,如何在使用Visual Studio编译器的编译时确定这些元素的类型大小。sizeof不能在第一个元素上使用,因为向量可能为空。
对于clang和gcc,我可以执行以下操作:
#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);
}
Run Code Online (Sandbox Code Playgroud)
使用O2,将在编译时对其进行优化以使其仅返回4。但是MSVC无法对其进行优化。是否可以通过更改此代码来实现?
在c ++ 11或更高版本中,您可以decltype(vect)::value_type用来获取元素的类型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;
}
Run Code Online (Sandbox Code Playgroud)
由于您希望MSVC square为类似于GCC生成的功能生成优化的代码,因此必须修改代码。
您可以删除函数模板size_of_vector_elements,并利用不评估其操作数的事实。sizeof
然后,您修改后的平方函数就变成这样:
int square(int num)
{
std::vector<unsigned> vector;
return sizeof(vector[0]);
}
Run Code Online (Sandbox Code Playgroud)
MSVC在/O2优化时为此功能生成的程序集是:
int square(int) PROC ; square, COMDAT
mov eax, 4
ret 0
int square(int) ENDP
Run Code Online (Sandbox Code Playgroud)
这类似于GCC在-O2优化时产生的结果。
square(int):
mov eax, 4
ret
Run Code Online (Sandbox Code Playgroud)
参见演示。
| 归档时间: |
|
| 查看次数: |
157 次 |
| 最近记录: |