4

I am trying to figure out if you can do this with templates:

template <typename T, (something here)>
void DoSomething(T& class_object)
{
    std::cout << class_object.(something here) << std::endl;
}

In other words, can you pass a member object you would like to access to the template somehow? I can't seem to find any examples anywhere. I know that you could do it with a macro:

#define DO_SOMETHING(T, member)
void DoSomething(T& class_object)
{
    std::cout << class_object.member << std::endl;
}

But I'd like to use templates if possible.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
tenspd137
  • 367
  • 1
  • 12

1 Answers1

5

Something along these lines:

template <typename T, auto T::*m>
void DoSomething(T& class_object)
{
    std::cout << (class_object.*m) << std::endl;
}

Demo

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
  • So the precondition for this is that `m` has to be a public member of struct/class right? – kiner_shah Mar 01 '23 at 05:40
  • 1
    Doesn't have to be public. The code that instantiates `DoSomething` needs to be able to access it; `DoSomething` itself doesn't need any special access. E.g. a method of a class could call it, passing the pointer to a private member. [Demo](https://godbolt.org/z/KGz7qaTcc) – Igor Tandetnik Mar 01 '23 at 13:10
  • So - I just realized I am stuck on C++ 14 for now - is there a way to do this without the auto specifier? –  tenspd137 Mar 01 '23 at 15:44
  • Ahhh - found it for C++14: https://stackoverflow.com/questions/32119056/passing-a-pointer-to-class-member-as-a-template-parameter –  tenspd137 Mar 01 '23 at 17:34