小编has*_*sdf的帖子

C++:将指针转换为int并稍后再返回指针是否安全?

将指针转换为int并稍后再返回指针是否安全?

如果我们知道指针是否为32位长且int是32位长怎么样?

long* juggle(long* p) {
    static_assert(sizeof(long*) == sizeof(int));
    int v = reinterpret_cast<int>(p); // or if sizeof(*)==8 choose long here
    do_some_math(v); // prevent compiler from optimizing
    return reinterpret_cast<long*>(v);
}

int main() {
    long* stuff = new long(42);
    long* ffuts = juggle(stuff); 
    std::cout << "Is this always 42? " << *ffuts << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这是否包含在标准中?

c++ pointers

24
推荐指数
4
解决办法
1万
查看次数

如何在一个列表中存储不同的数据类型?(C++)

我需要存储一个对象的各种属性的列表.属性由名称和数据组成,可以是任何数据类型.

我知道我可以创建一个类"Property",并使用不同的PropertySubClasses扩展它,它们只与它们存储的数据类型不同,但感觉不对.

class Property
{
     Property(std::string name);
     virtual ~Property();

     std::string m_name;
};

class PropertyBoolean : Property
{
     PropertyBoolean(std::string name, bool data);

     bool m_data;
};

class PropertyFloat : Property
{
     PropertyFloat(std::string name, float data);

     float m_data;
};

class PropertyVector : Property
{
     PropertyVector(std::string name, std::vector<float> data);

     std::vector<float> m_data;
};
Run Code Online (Sandbox Code Playgroud)

现在我可以存储各种属性

 std::vector<Property*>
Run Code Online (Sandbox Code Playgroud)

为了获取数据,我可以将对象强制转换为子类.或者我可以创建一个纯虚函数来处理函数内部的数据,而无需进行转换.

无论如何,创建这些不同类型的子类是不对的,这些子类仅因它们存储的数据类型而不同.有没有其他方便的方法来实现类似的行为?

我没有访问Boost.

c++ data-structures

21
推荐指数
2
解决办法
4万
查看次数

四元数和三轴

给定一个四元数 q 和三个 3D 向量 (vx, vy, vz),它们形成坐标轴,可以沿任意方向定向,但都彼此垂直,从而形成 3d 空间。

如何检查四元数 q 是否旋转到与某些 3D 向量(vx、vy、vz)相同的方向(或相反的方向)?

math quaternions computational-geometry

5
推荐指数
1
解决办法
1394
查看次数