Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you specify class a member as template parameter? [duplicate]

Tags:

c++

templates

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.

like image 414
tenspd137 Avatar asked Sep 19 '25 08:09

tenspd137


1 Answers

Something along these lines:

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

Demo

like image 70
Igor Tandetnik Avatar answered Sep 21 '25 23:09

Igor Tandetnik