gpt4 book ai didi

c++ - 是否可以根据构造函数中作为参数传入的 bool 将数据成员初始化为 const?

转载 作者:行者123 更新时间:2023-12-02 18:38:35 30 4
gpt4 key购买 nike

我有一个类,它接受一个名为 fixed 的 bool 值作为参数。如果 fixed 为 true,我希望它将数据成员 position 初始化为 const。这可能吗?

class PhysicsVertex 
{
public:
PhysicsVertex(olc::vf2d position, const bool fixed = false) :
position(position), fixed(fixed)
{
}
olc::vf2d position; //make this const if fixed is true.
const bool fixed = false;
};

int main()
{
PhysicsVertex v1{ {0, 0}, true }; //initialize v1.position as const
PhysicsVertex v1{ {0, 0} }; //initialize v1.position as non-const
}

最佳答案

如果在编译时需要有关fixed参数的信息,那么您可以使用模板

#include <type_traits>

struct vf2d
{
};
template <bool fixed>
class PhysicsVertex
{
public:
PhysicsVertex() :
position()
{
}
typename std::conditional<fixed, const vf2d, vf2d>::type position;
};

void foo()
{
auto vertex = PhysicsVertex<true>();
// vertex.position = vf2d(); - compile time error, you cannot change const member
auto vertex2 = PhysicsVertex<false>();
vertex2.position = vf2d(); // It works fine, you can change non const member
}

关于c++ - 是否可以根据构造函数中作为参数传入的 bool 将数据成员初始化为 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68393256/

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