Voko
Voko

Reputation: 778

C++ pass pointer to member as template argument

I have a bunch of very similar functions:

void foo1(Obj o) {
    bar(o.a);
}

void foo2(Obj2 o) {
    bar(o.b);
}

void foo3(Obj3 o) {
    bar(o.c);
}

How can I reduce the duplicating of code? Can I do something like:

template<typename T, pointerToMember>
void foo(T o) {
    bar(o.pointerToMember);
}

And then create all functions like:

foo<Obj, Obj.x>;
...

?

Upvotes: 1

Views: 78

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122298

Yes it is possible to have a pointer to member as template parameter:

#include <string>

struct Obj {
    int a,b,c;
};

void bar(int x){}

template<typename T, int (T::*pointerToMember)>
void foo(T o) {
    bar(o.*pointerToMember);
}
int main() {
    Obj x;
    foo<Obj,&Obj::a>(x);
}

However, there are different ways that would make the call less verbose. You could pass the member pointer as parameter to be able to deduce it, that would allow to call it as

foo(x,&Obj::a);

Last not least, you could call bar directly

bar(x.a);

Upvotes: 2

Related Questions