Nested data member pointer - not possible? - c++

The following reduced code sample does not do anything useful but two subsequent assignments to a data member pointer. The first assignment works, the second one gives a compiler error. Presumably because its to a nested member.
Question would be: Is it really just not possible to let a member pointer point to a nested member or am I missing any fancy syntax there?
struct Color {
float Red;
float Green;
float Blue; };
struct Material {
float Brightness;
Color DiffuseColor; };
int main() {
float Material::* ParamToAnimate;
ParamToAnimate = &Material::Brightness; // Ok
ParamToAnimate = &Material::DiffuseColor.Red; // Error! *whimper*
return 0; }
ATM I am working around by using byte offsets and a lot of casts. But that is ugly, I would better like to use those member pointers.
Yes, I know that question surely arised before (like nearly any question). Yes, I searched beforehand but found no satisfying answer.
Thanks for your time.

AFAIK, this is not possible. A pointer-to-member can only be formed by an expression of type &qualified_id, which is not your case.
Vite Falcon's solution is probably the most appropriate.

I assume you are trying to get the pointer to the datamember Red. Since this is defined in the struct Color the type of the pointer is Color::*. Hence your code should be:
int main() {
float Color::* ParamToAnimate;
ParamToAnimate = &Color::Red;
return 0; }
To use it, you need to bind it to an instance of Color for example:
void f(Color* p, float Color::* pParam)
{
p->*pParam = 10.0;
}
int main() {
float Color::* ParamToAnimate;
ParamToAnimate = &Color::Red;
Material m;
f(&m.DiffuseColor, ParamToAnimate);
return 0;
}
EDIT: Is it not possible to make the animation function a template? For example:
template<class T>
void f(T* p, float T::* pParam)
{
p->*pParam = 10.0;
}
int main() {
Material m;
f(&m.DiffuseColor, &Color::Red);
f(&m, &Material::Brightness);
return 0;
}

Instead of a member pointer, you can use a functor that returns a float* when given an instance of Material; change the type of ParamToAnimate to something like:
std::function<float*(Material&)>
On the plus side, it's portable - but on the downside, it requires a significant amount of boilerplate code and has significant runtime overhead.
If this is performance critical, I'd be tempted to stick with the offset method.

Basically you're trying to get a pointer to a float variable that you can animate. Why not use float*. The issue you're having there is that Brightness is a member of Material, however, Red is a member of Color and not Material, to the compiler. Using float* should solve your problem.

It's not possible. But there is a workaround very close to what you want to achieve. It involves putting the nested member into an union alongside with a "layout-compatible" anonymous struct. The downside is a bit bloated interface and the need of keeping definitions of sibling structs in sync.
struct Color {
float Red;
float Green;
float Blue; };
struct Material {
float Brightness;
union {
struct { // "Layout-compatible" with 'Color' (see citation below)
float DiffuseColorRed;
float DiffuseColorGreen;
float DiffuseColorBlue; };
Color DiffuseColor; }; };
int main() {
Material M;
float Material::* ParamToAnimate;
ParamToAnimate = &Material::DiffuseColorRed;
std::cin >> M.*ParamToAnimate;
std::cout << M.DiffuseColor.Red << std::endl;
return 0; }
ISO IEC 14882-2003 (c++03):
§3.9
11
If two types T1 and T2 are the same type, then T1 and T2 are
layout-compatible types. [Note: Layout-compatible enumerations are
described in 7.2. Layout-compatible POD-structs and POD-unions are
described in 9.2. ]
§9.2
16
If a POD-union contains two or more POD-structs that share a common
initial sequence, and if the POD-union object currently contains one
of these POD-structs, it is permitted to inspect the common initial
part of any of them. Two POD-structs share a common initial sequence
if corresponding members have layout-compatible types (and, for
bit-fields, the same widths) for a sequence of one or more initial
members.
Multiple nesting is possible too:
struct Color {
float Red;
float Green;
float Blue; };
struct Material {
float Brightness;
Color DiffuseColor; };
struct Wall {
union {
struct {
float SurfaceBrightness;
struct {
float SurfaceDiffuseColorRed;
float SurfaceDiffuseColorGreen;
float SurfaceDiffuseColorBlue; }; };
Material Surface; }; };
int main() {
Wall W;
float Wall::* ParamToAnimate;
ParamToAnimate = &Wall::SurfaceDiffuseColorRed;
std::cin >> W.*ParamToAnimate;
std::cout << W.Surface.DiffuseColor.Red << std::endl;
return 0; }
§9.2
14
Two POD-struct (clause 9) types are layout-compatible if they have the
same number of nonstatic data members, and corresponding nonstatic
data members (in order) have layout-compatible types (3.9).

How about inheritance instead of composition?
struct Color {
float Red;
float Green;
float Blue; };
struct DiffuseColor : public Color {
};
struct Material : public DiffuseColor {
float Brightness; };
int main() {
float Material::* ParamToAnimate;
ParamToAnimate = &Material::Brightness; // Ok
ParamToAnimate = &Material::DiffuseColor::Red; // Ok! *whew*
return 0; }

You could simply refactor such that you don't have the nested structure at all. Add a setter than unpacks the color into its component parts so that existing code need not change much, and go from there.
You could also take an optional second pointer that digs into the nested type. A single test to see if you need the second parameter may prove good enough compared to your current method, and would be more easily extended should additional fields turn up later.
Take that a step further, and you have a base MaterialPointer class with a virtual Dereference method. The case class can handle simple members, with derived classes handling nested members with whatever additional information they need to find them. A factory can then produce MaterialMember* objects of the appropriate type. Of course, now you're stuck with heap allocations, so this is likely a little too far to be practical.

Since at some point you need a pointer to the actual data, this may or may not work for you:
float Material::* ParamToAnimate;
ParamToAnimate = &Material::Brightness; // Ok
float Color::* Param2;
Param2 = &Color::Red;
Material mat;
mat.Brightness = 1.23f;
mat.DiffuseColor.Blue = 1.0f;
mat.DiffuseColor.Green = 2.0f;
mat.DiffuseColor.Red = 3.0f;
float f = mat.DiffuseColor.*Param2;

Related

How would one succinctly compare the values of and call the functions of many derived classes' base class?

I have a 2d physics engine that I've been programming in C++ using SFML; I've implemented a rough collision detection system for all SandboxObjects (the base class for every type of physics object), but I have a dilemma.
I plan to have many different derived classes of SandboxObjects, such as Circles, Rects, and so on, but I want a way to check if the roughHitbox of each SandboxObject collides with another.
When the program starts, it allocates memory for, let's say, 10,000 Circles
int circleCount = 0;//the number of active Circles
constexpr int m_maxNumberOfCircles = 10000;//the greatest number of circles able to be set active
Circle* m_circles = new Circle[m_maxNumberOfCircles];//create an array of circles that aren't active by default
like so.
and every time the user 'spawns' a new Circle, the code runs
(m_circles + circleCount)->setActive();`
circleCount++
Circles that aren't alive essentially do not exist at all; they might have positions and radii, but that info will never be used if that Circle is not active.
Given all this, what I want to do is to loop over all the different arrays of derived classes of SandboxObject because SandboxObject is the base class which implements the rough hitbox stuff, but because there will be many different derived classes, I don't know the best way to go about it.
One approach I did try (with little success) was to have a pointer to a SandboxObject
SandboxObject* m_primaryObjectPointer = nullptr;
this pointer would be null unless there were > 1 SandboxObjects active; with it, I tried using increment and decrement functions that checked if it could point to the next SandboxObject, but I couldn't get that to work properly because a base class pointer to a derived class acts funky. :/
I'm not looking for exact code implementations, just a proven method for working with the base class of many different derived classes.
Let me know if there's anything I should edit in this question or if there's any more info I could provide.
Your problems are caused by your desire to use a polymorphic approach on non-polymorphic containers.
The advantage of a SandboxObject* m_primaryObjectPointer is that it allows you to treat your objects polymorphicaly: m_primaryObjectPointer -> roughtHitBox() will work regardless of the object's real type being Circle, Rectangle, or a Decagon.
But iterating using m_primaryObjectPointer++ will not work as you expect: this iteration assumes that you iterate over contiguous objects in an array of SandboxObject elements (i.e. the compiler will use the base type's memory layout to compute the next address).
Instead, you may consider iterating over a vector (or an array if you really want to deal with extra memory management hassle) of pointers.
vector<SandboxObject*> universe;
populate(universe);
for (auto object:unviverse) {
if (object->isActive()) {
auto hb = object -> roughtHitBox();
// do something with that hitbox
}
}
Now managing the objects in the universe can be painful as well. You may therefore consider using smart pointers instead:
vector<shared_ptr<SandboxObject>> universe;
(little demo)
It's hard to answer this without knowing the requirements but you could have sandbox maintain two vectors of active and inactive objects, and use unique_ptrs of the base class for memory management.
Some code below:
#include <vector>
#include <memory>
#include <iostream>
class sandbox_object {
public:
virtual void do_something() = 0;
};
class circle : public sandbox_object {
private:
float x_, y_, radius_;
public:
circle(float x, float y, float r) :
x_(x), y_(y), radius_(r)
{}
void do_something() override {
std::cout << "i'm a circle.\n";
}
};
class triangle : public sandbox_object {
private:
float x1_, y1_, x2_, y2_, x3_, y3_;
public:
triangle( float x1, float y1, float x2, float y2, float x3, float y3) :
x1_(x1), y1_(y1), x2_(x2), y2_(y2), x3_(x3), y3_(y3)
{}
void do_something() override {
std::cout << "i'm a triangle.\n";
}
};
class sandbox {
using sandbox_iterator = std::vector<std::unique_ptr<sandbox_object>>::iterator;
private:
std::vector<std::unique_ptr<sandbox_object>> active_objects_;
std::vector<std::unique_ptr<sandbox_object>> inactive_objects_;
public:
void insert_circle(float x, float y, float r) {
active_objects_.push_back( std::make_unique<circle>(x, y, r) );
}
void insert_triangle(float x1, float y1, float x2, float y2, float x3, float y3) {
active_objects_.push_back( std::make_unique<triangle>(x1,y1,x2,y2,x3,y3));
}
sandbox_iterator active_objs_begin() {
return active_objects_.begin();
}
sandbox_iterator active_objs_end() {
return active_objects_.end();
}
void make_inactive(sandbox_iterator iter) {
std::unique_ptr<sandbox_object> obj = std::move(*iter);
active_objects_.erase(iter);
inactive_objects_.push_back(std::move(obj));
}
};
int main() {
sandbox sb;
sb.insert_circle(10.0f, 10.0f, 2.0f);
sb.insert_triangle(1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 1.0f);
sb.insert_circle(1.0f, 6.0f, 4.0f);
sb.make_inactive(sb.active_objs_begin());
(*sb.active_objs_begin())->do_something(); // this should be the triangle...
return 0;
}

C++ is there way to access a std::vector element by name?

I am experimenting with a simple vertex class.
class Vertex
{
public:
std::vector<float> coords;
//other functionality here - largely irrelevant
};
And lets say we create a Vertex object as below:
Vertex v0(1.f, 5.f, 7.f);
I am wondering if there is anyway to assign a name to each element of a vector?
Let's say that each std::vector will only ever have a size of 3. I know I can access an element or index of the vector in a way such as v0.coords[0] through to v0.coords[2];
However, I am wondering if there is a way in which I could assign a name to each element of the vector, ie:
v0.coords.x == v0.coords[0];
v0.coords.y == v0.coords[1];
v0.coords.z == v0.coords[2];
So that if I was to access the vector, I could access via a name rather than an index.
Is such a thing possible? If so, how do I go about creating such aliasing?
I am wondering if there is anyway to assign a name to each element of a vector?
No, there is not. At least, not the way you want.
I suppose you could use macros, eg:
#define coords_x coords[0]
#define coords_y coords[1]
#define coords_x coords[2]
Now you can use v0.coords_x, v0.coords_y, and v0.coords_z as needed.
Or, you can use getter methods, eg:
class Vertex
{
public:
vector<float> coords;
//other functionality here - largely irrelevant
float& x(){ return coords[0]; }
float& y(){ return coords[1]; }
float& z(){ return coords[2]; }
};
Now you can use v0.x(), v0.y(), and v0.z() as needed.
But really, in this situation, there is just good no reason to use a vector at all. It is simply the wrong tool for the job. Use a struct instead, eg:
struct Coords
{
float x;
float y;
float z;
};
class Vertex
{
public:
Coords coords;
//other functionality here - largely irrelevant
};
Alternatively:
class Vertex
{
public:
struct
{
float x;
float y;
float z;
} coords;
//other functionality here - largely irrelevant
};
Now you can use v0.coords.x, v0.coords.y, and v0.coords.z as needed.

Structure constructor in other structure

I am trying to create Voronoi diagram for some given points. Each points have different attributes and I want to denote it as color. To map my own Point structure with Boost Point concept, I have written some code. I have the following setup:
struct Point {
double a;
double b;
Point(double x, double y) : a(x), b(y) {}
};
// This Point structure is mapped to Boost Point concept. Code emitted
I have another structure as :
struct Point_Collection {
Point xy(double x, double y);
short color;
};
Visual Studio created an automatic definition as :
Point Point_Collection::xy(double x, double y)
{
return Point();
}
Now if I try to instantiate an object of Point_collection as:
std::vector<Point_Collection> *test;
test = new std::vector<Point_Collection>();
Point_Collection xy_color;
for (int i = 0; i < 5000; i++) {
xy_color.xy(rand() % 1000, rand() % 1000);
xy_color.color = rand() % 17;
test->push_back(xy_color);
}
I get an error.
error C2512: 'Point': no appropriate default constructor available
Can someone point me in the right direction why is this happening?
Point xy(double x, double y); declares a member function in Point_Collection that is identified by xy, accepts two doubles and returns a Point object by value.
If you want a simple aggregate that holds a point, the C++11 and onward way would be to define it like this:
struct Point_Collection {
Point xy;
short color;
};
Point_Collection xy_color{ { rand()%100, rand()%100 }, static_cast<short>(rand()%16)};
The above is a simple aggregate initialization using value initialization syntax. You should prefer it for two reasons:
It will not allow narrowing conversions. (Which int to short is, therefore the cast).
It's easy to implement. It requires no typing if your class has all public members.
(Also rand has better alternatives in C++11, check out the header <random>)
If you don't have access to C++11, then you can either write a constructor for Point_Collection.
struct Point_Collection {
Point xy;
short color;
Point_Collection(Point xy, short color)
: xy(xy), color(color) {}
};
Point_Collection xy_color (Point(...,...), ...);
Or use aggregate initialization with more verbose syntax:
struct Point_Collection {
Point xy;
short color;
};
Point_Collection xy_color = { Point(rand()%100, rand()%100), rand()%16 };
(Since the above is C++03, rand()%16 will be silently converted to short, despite it being narrowing).

Changing values in polymorphic boost::shared_ptr (inside std::vector)

I have the following base calibration struct:
struct Standard
{
public:
unsigned long ulCamID;
std::string sCalibrationModel;
float fC;
float fXh;
float fYh;
Standard()
{
ulCamID = 0;
fC = fXh = fYh = 0.0;
}
virtual ~Standard()
{
}
};
And derived structs such as:
struct Aus: public Standard
{
public:
float fK1;
float fK2;
float fK3;
float fP1;
float fP2;
float fB1;
float fB2;
Aus()
{
fC = fXh = fYh = fK1 = fK2 = fK3 = fP1 = fP2 = fB1 = fB2 = 0.0;
}
};
Because I do not know at compile how many Calibrations I will need, nor which calibration models, I thought it convenient to put it into a std::vector and use boost::shared_ptr to point to them. I do this like so:
typedef boost::shared_ptr<CalibrationModels::Standard> shr_ptr;
std::vector<shr_ptr> vec;
shr_ptr p(new CalibrationModels::Aus);
vec.push_back(p);
p.reset(new CalibrationModels::Brown);
vec.push_back(p);
This seems to work fine (the debugger reports that the pointers inside the vector point to the derived struct). However, I have difficulties now to access/change the values inside the vector. If I try something like this:
boost::dynamic_pointer_cast<CalibrationModels::Aus>(vec.at(0)).px->fK3 = 1.3221e-9
It tells me that px is private ( ‘boost::shared_ptr::element_type* boost::shared_ptr::px’ is private element_type * px; ).
What is the proper way to access and manipulate the values inside those pointers to derived structs?
The problem you have is that px is a private member of the smart pointer. To access your class boost provides the -> operator. You can use that to access the pointer as you would use it for a regular pointer. This would change your line to this:
boost::dynamic_pointer_cast<CalibrationModels::Aus>(vec.at(0))->fK3 = 1.3221e-9;
^^ Difference here
Note that, if you actually need the value, you can use the get() method to get the pointer that is stored in the shared_ptr.

Array of values within an ENUM?

I have this code
enum type {NOTHING, SOMETHING, SOMETHINGELSE}
type *x;
At the moment I use x[765] == SOMETHING for example, How would I store other values for example
x[765] == SOMETHINGELSE;
x[765].position == 43.5;
x[765].somevar == 12;
I will apologize for my poor wording within my question im just starting out in C++, I know what I want i'm just not to sure on how to ask it.
Thanks.
It looks as if you're looking for a way to structure 'knowledge'; this is done with a struct or a class:
#include <vector>
struct Info {
enum thingness { nothing, something };
// 'member' variables
thingness howMuch;
int a_counter;
float position;
};
int main(){
Info object;
object.howMuch=Info::something;
object.a_counter=1;
object.position=5.4;
You can group these kinds of objects into a container - typically an std::vector:
// a container of InterestingValues
std::vector<Info> container(300);
container[299].howMuch=Info::nothing;
container[299].a_counter=4;
container[299].position = 3.3;
// or assign rightaway:
container[2] = object;
}
You will have to make yourself a more complex type:
struct type
{
enum flag_type
{
NOTHING, SOMETHING, SOMETHINGELSE
} flag;
double position;
int somevar;
};
and later have an array of this new type.
Get yourself a good book to learn from. A list of good books is available here: The Definitive C++ Book Guide and List
In C++, you are asking how to declare an array of structures. Try this:
struct type {
double position;
int somevar;
};
type *x;
x[765].position = 43.5;
x[765].somevar = 12;
An enum is a replaceable label basically for an int. You need to define a struct or a class.
struct type
{
float position ;
};
type var;
var.position = 3.4;
Your type enum would need to be a member of a class, along with the other fields. For example,
class MyType
{
public:
type t;
double position;
int somevar;
};
With an array of MyType instances
MyType *x;
you would then be able to do what you ask expect you would need to do
x[765].t = SOMETHINGELSE;
to assign to the enum.