这个带有模板<类 Vector 的C++代码片段有什么问题>

What is wrong in this C++ code snippet with template<class Vector>

本文关键字:代码 C++ 片段 什么 gt 问题 Vector lt      更新时间:2023-10-16

在这里,我只是使用 test(( 函数并将向量传递给它。 在测试函数中使用 decltype(( 来推断类型,但输出是完全神秘的。

#include <vector>
#include <stdio.h>
template<class Vector>
void test(Vector& vec)
{
using E = decltype(vec[0]);
for (int i=0; i < 10; ++i) {
vec.push_back(E(i));
}
}
int main() {
std::vector<double> v;
test(v);
for (int i=0; i < 10; ++i) {
printf("%fn", v[i]);
}
}

Edouble&,而不是double,如将push_back行更改为

vec.push_back(static_cast<E>(i));

"错误:从类型'int'到类型'E'{又名'double&'}的无效static_cast">

正因为如此,您实际上是在修改double的内部表示,就好像您在使用reinterpret_cast一样。应使用static_cast在值之间进行转换。

请改用以下任一定义:

using E = std::remove_reference_t<decltype(vec.at(0))>;
using E = typename Vector::value_type;