I am wondering if there is a way I could possibly pass a field name to a function template. Consider the following:
struct Type1{
unsigned int Field1;
unsigned int Field2;
};
struct Type2{
unsigned int Field2;
unsigned int Field3;
};
template <typename TYPE>
bool MyFunction(TYPE _Type){
if(_Type.Field1==5)
return false;
}
This works fine, however within MyFunction
I am specifying .Field1
, is there a way I can pass the name of this field into a template, for example:
void TestFunction(){
Type1 mt1;
MyFunction(mt1, Field1);
}
Clearly, I'm not templating a type here, and I'm at a loss on what this would be called (other than the obvious answer - silly!) so I'm struggling to even search for a solution.
You can't pass in pure names, because names are not part of the C++ meta-model, but you can pass pointers-to-members to your function:
template <typename TYPE, typename T>
bool MyFunction(TYPE obj, T TYPE::*mp)
// ^^^^^^^^^
{
if ((obj.*mp) == 5)
// ^^^^
return false;
// ... <== DON'T FORGET TO RETURN SOMETHING IN THIS CASE,
// OTHERWISE YOU WILL GET UNDEFINED BEHAVIOR
}
Here is how you would use it in a small, complete program:
struct Type1{
unsigned int Field1;
unsigned int Field2;
};
struct Type2{
unsigned int Field2;
unsigned int Field3;
};
int main()
{
Type1 t1;
Type2 t2;
MyFunction(t1, &Type1::Field1);
MyFunction(t2, &Type2::Field3);
}
And here is a live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With