wjd*_*wjd 5 c++ reference variable-assignment
是否可以在C++中使用不同的名称引用相同的变量而不使用预处理器?
实现与此伪代码相同的效果
struct vec3f {
float[3] values;
};
struct color : public vec3f {
#define r values[0]
#define g values[1]
#define b values[2]
};
color c;
c.r = 0.5f;
Run Code Online (Sandbox Code Playgroud)
以下具有正确的语义,除了它在结构中为3个引用分配空间:
struct color : public vec3f {
float& r;
float& g;
float& b;
color() : r(values[0]), g(values[1]), b(values[2]) { }
};
Run Code Online (Sandbox Code Playgroud)
有没有办法在不增加结构大小的情况下获得此编译时名称替换?
Ben*_*igt 10
这个怎么样?
struct vec3f {
float[3] values;
};
struct color : public vec3f
{
float& r() { return values[0]; }
float& g() { return values[1]; }
float& b() { return values[2]; }
const float& r() const { return values[0]; }
const float& g() const { return values[1]; }
const float& b() const { return values[2]; }
};
Run Code Online (Sandbox Code Playgroud)