Passing a field name to a function template

I am wondering if there is a way to pass the field name into 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 in MyFunction I tell .Field1 if there is a way to pass the name of this field to the template, for example:

 void TestFunction(){ Type1 mt1; MyFunction(mt1, Field1); } 

It’s clear that I’m not a template for the type here, and I’m at a loss that it will be caused (except for the obvious answer - it's stupid!), So I'm struggling to find a solution.

+7
source share
2 answers

You cannot pass pure names because the names are not part of the C ++ metamodel, but you can pass member pointers 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's how you could 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 living example .

+11
source

You can pass a pointer to an element :

 template <typename T> bool MyFunction(T& type, int T::*field){ if (type.*field == 5) return false; } MyFunction(mt1, &Type1::Field1); 
+5
source

All Articles