gpt4 book ai didi

c++ - C++::安全地使用reinterpret_cast生成 “wrapper”迭代器

转载 作者:行者123 更新时间:2023-12-02 10:06:45 25 4
gpt4 key购买 nike

我有一个包含给定原始类型值的 vector ,但是我想对该 vector 进行迭代,以便可以“好像”使用某些包装值类型的类来执行某些操作。

下面的代码示例编译并产生预期的结果:

#include <iostream>
#include <vector>

template<class T>
struct wrap
{
T x;

void print() const
{
if (x < 0)
std::cout << " negative ";
else if (x > 0)
std::cout << " positive ";
else
std::cout << " --null-- ";
}

void operator ++ ()
{
if (this->x < static_cast<T>(0))
this->x += static_cast<T>(1000);
}
};


int main()
{
using vec_t = std::vector<int>;
vec_t v;
v.push_back(-1234);
v.push_back( 5678);
v.push_back(-4);
v.push_back(0);

// essential piece of code
using vec_w = std::vector< wrap<int> >;
vec_w::iterator it = reinterpret_cast<vec_w*>(&v)->begin();
vec_w::iterator ti = reinterpret_cast<vec_w*>(&v)->end();

while (it != ti)
{
it->print();
++(*it);
it->print();
std::cout << std::endl;
++it;
}

return 0;
}

输出:
 negative  negative 
positive positive
negative positive
--null-- --null--

但是,只要包装程序定义了完全相同的值类型(就别无其他),这样使用就安全吗?

最佳答案

But is this safe to use, as long as the wrapper defines the exact same value type (and nothing else)?



不。您违反了严格的别名规则。

为什么不包装 T&
template<class T>
struct wrap
{
T& x;

void print() const
{
if (x < 0)
std::cout << " negative ";
else if (x > 0)
std::cout << " positive ";
else
std::cout << " --null-- ";
}

void operator ++ ()
{
if (this->x < static_cast<T>(0))
this->x += static_cast<T>(1000);
}
};

您可以包裹一个循环
int main() 
{
std::vector<int> v;
v.push_back(-1234);
v.push_back( 5678);
v.push_back(-4);
v.push_back(0);

for (auto & i : v)
{
wrap<int> w { i };
w.print();
++w;
w.print();
std::cout << std::endl;
}

return 0;
}

或有包裹的 vector
int main() 
{
std::vector<int> v;
v.push_back(-1234);
v.push_back( 5678);
v.push_back(-4);
v.push_back(0);

std::vector<wrap<int>> w { v.begin(), v.end() };

for (auto & i : w)
{
i.print();
++i;
i.print();
std::cout << std::endl;
}

return 0;
}

关于c++ - C++::安全地使用reinterpret_cast生成 “wrapper”迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59859075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com