Piodo
Piodo

Reputation: 616

Access to structure field in another structure

Suppose I have structures

struct A
{
  int x;
};

and it is possible to refer to x field by &A::x

My question is, Can I do something similar (refer to x) in case below (C++14)? :

struct A
{
  struct B
  {
    int x;
  };

  B b;
};

Okay, so there's more complex example:

This works:

struct A
{
    int x;
};

template <typename U, typename V, typename W>
void setField(U& object, V U::* field, W&& value)
{
    object.*field = std::forward<W>(value);
}

int main()
{
  auto x = 5;
  A a;
  a.x = 0;
  std::cout << a.x << std::endl;
  setField(a, &A::x, x);
  std::cout << a.x << std::endl;
}

and when I want to get deeper variable, it doesn't:

struct A
{
    struct B
    {
        enum myEnum
        {
            E_0 = 0,
            E_1 = 1
        };
        myEnum e;
    };
    B b;
};

template <typename U, typename V, typename W>
void setField(U& object, V U::* field, W&& value)
{
    object.*field = std::forward<W>(value);
}

int main()
{
  auto m_enum = A::B::myEnum::E_0;
  A a;
  a.b.e = m_enum;
  std::cout << a.b.e << std::endl;
  setField(a, &A::B::e, m_enum);
  std::cout << a.b.e << std::endl;
}

Error log:

31:31: error: no matching function for call to 'setField(A&, A::B::myEnum A::B::*,A::B::myEnum&)'

31:31: note: candidate is:

20:6: note: template<class U, class V, class W> void setField(U&, V U::*, W&&)

20:6: note: template argument deduction/substitution failed:

31:31: note: deduced conflicting types for parameter 'U' ('A' and 'A::B')

Upvotes: 0

Views: 104

Answers (2)

bladzio
bladzio

Reputation: 424

You should write:

setField(a.b, &A::B::e, m_enum);

instead of

setField(a, &A::B::e, m_enum);

Upvotes: 2

rubenvb
rubenvb

Reputation: 76579

You can simply do

&A::B::x

This gives you an address to x inside A::B. To evaluate it, you need an object of type A::B, which in your case can be accessed by &A::b evaluated on an object of type A. You'll thus need to levels of dereferencing.

Upvotes: 1

Related Questions