Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the field name into a function template

Tags:

c++

templates

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.

like image 567
R4D4 Avatar asked Mar 09 '13 18:03

R4D4


1 Answers

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.

like image 54
Andy Prowl Avatar answered Sep 18 '22 15:09

Andy Prowl