Is it possible to have this code work somehow? (Current get a compile error stating MMVertex2F4B2F does not exist) I don't want to wrap the 2 within another struct as that will effect the usability of the class within my existing code.
I need this all to happen at compile time, essentially the TemplatedClass needs to hold data regarding it's outer class that I can access later by creating an instance of TemplatedClass.
struct MMVertex2F4B2F
{
MMPoint vertex;
MMColor4B col;
MMPoint tex;
struct TemplatedClass<offsetof(MMVertex2F4B2F, vertex)> {};
};
Regards, James
you could put the data of your main class into a sub-type:
struct MMVertex2F4B2F
{
struct MMVertexData {
MMPoint vertex;
MMColor4B col;
MMPoint tex;
} Data;
struct TemplatedClass<offsetof(MMVertexData, vertex)> {};
};
(if you access the data members via member methods, you only have to adapt those to this change instead of all of your code)
Alternatively, the TemplatedClass<>
could be declared standalone (not a sub-type) similar to a traits template.
The fact that your code doesn't work shows that its design is flawed.
Note that
struct TemplatedClass<offsetof(MMVertex2F4B2F, vertex)> {};
isn't valid C++ code. Either this is a template specialization, which would be
template <> struct TemplatedClass<offsetof(MMVertex2F4B2F, vertex)> {};
(which doesn't seem like it would make much sense in this context) it's should be a declaration of an instance of the template, which would be
TemplatedClass<offsetof(MMVertex2F4B2F, vertex)> myInstanceVar;
For the rest, I agree with Walter's answer.
The offsetof
macro is inherited from C, and it does work with POD structs, but it's not the best approach to referencing a member in C++. Parameterize the template on pointer-to-members.
template< typename client, MMPoint client ::* > // PTM parameter
struct TemplatedClass {
…
};
struct MMVertex2F4B2F
{
MMPoint vertex;
MMColor4B col;
MMPoint tex;
// PTM argument acceptable despite incomplete class:
TemplatedClass<MMVertex2F4B2F, & MMVertex2F4B2F::vertex> template_inst;
};
The template in this example accepts a pointer to member of type MMPoint
within any specified class. You might use some other parameterization. Anything is better than byte offsets and casting through char *
.
After sleeping on it I came to this solution which seems to work:
struct MMVertex2F4B2F
{
MMPoint vertex;
MMColor4B col;
MMPoint tex;
struct TemplatedClass; //Use a forward declaration here
};
//The template will now work as MMVertex2F4B2F is fully declared
struct MMVertex2F4B2F::TemplatedClass
: public VertDef <offsetof(MMVertex2F4B2F, vertex)> {};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.