0

I am a situation where I am trying to implement something I'm not sure is supported by C++.

Say for example:

class foo 
{
   public:
     type item1;
     type item2;
}

class fooList
{
   public:
     foo list;  
   type getFooMember(member)
   {
      return list.member
   }
}

Is there a way to write a function "getFooMember"? Essentially I am writing a templated binary search tree. I am looking to store items of the same type, however, one object of the class will store by name and the other will store by month. I wanted to reduce repetitive code. The easiest solution I can think of is:

type getFooItemOne()
{
   return list.item1;
}
type getFooItemTwo()
{
   return list.item2;
}

However, my add and search functions are around 20 lines and I wanted to see if I could avoid that.

Thanks guys

1
  • 1
    If you are storing multiple items of the same type, you should use an array or vector to store the elements. much easier to access it that way generically Commented May 9, 2016 at 0:04

1 Answer 1

1

The language feature that you're looking for is pointer to data member. The syntax is:

type getFooMember(type foo::*member) {
    return list.*member;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good: a better way is usually to take an arbitrary projection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.