Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A confusing typedef involves class scope

I'm reading code of a C++ project and it contains some code of the following form:

namespace ns {     class A {};     class B {}; }  struct C {     typedef ns::A* ns::B::* type; }; 

Can someone explain the meaning of the typedef line? type seems to be some kind of pointer to member of ns::B which points to ns::A, but I'm not sure.

Class A and B in the real code are not empty, but I think it's not relevant here. And here is a live example.

like image 643
Tien Avatar asked Nov 17 '15 18:11

Tien


People also ask

Does typedef have scope?

A typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.

Can we use typedef in class?

In C++, a typedef name must be different from any class type name declared within the same scope. If the typedef name is the same as a class type name, it can only be so if that typedef is a synonym of the class name. A C++ class defined in a typedef definition without being named is given a dummy name.


2 Answers

ns::B::* 

is a pointer-to-member-variable of B. Then ns::A* is its type.

So the whole declaration means

pointer-to-member-variable of B of type ns::A*

like image 200
vsoftco Avatar answered Oct 04 '22 13:10

vsoftco


The answer by @vsoftco already answers the core of the question. This answer shows how one might use such a typedef.

#include <iostream> #include <cstddef>  namespace ns {     struct A {};     struct B    {       A* a1;       A* a2;    }; }  struct C {    typedef ns::A* ns::B::*type; };  int main() {    C::type ptr1 = &ns::B::a1;    C::type ptr2 = &ns::B::a2;     ns::B b1;    b1.*ptr1 = new ns::A; // Samething as b1.a1 = new ns::A;     return 0; } 
like image 24
R Sahu Avatar answered Oct 04 '22 14:10

R Sahu