-2

I have the following code:

#include <iostream>

template<typename T>
void gaga(T * a){
    std::cout << "gaga(T * a)";
}

template<typename T> class A{};

template<typename T>
void gaga(A<T> & a){
    std::cout << "gaga(A<T> & a)\n";
}

template<typename T>
class B {
public:

    T * p;

    operator T*() const{
        std::cout << "Cast called" <<std::endl;
        return p;
    }
};

int main()
{
    B< A<int> > b;
    gaga(*b); /// WHAT IS GOING ON HERE? WHY is void gaga(A<T> & a) CALLED?

    A<int> * p;
    gaga(p); /// WHEN THE ABOVE calls void gaga(A<T> & a) WHY  is here 
             /// void gaga(T * a) CALLED???
}

And I am really puzzled why the gaga(A<T> & a) is called when I call it with *b which obviously results by the conversion operator in A<T> * but why?? ---> *b is a dereference operator not even defined!?? why can that be handed even to gaga(A<T> & a)?

Thanks for an explanation!

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Gabriel
  • 8,990
  • 6
  • 57
  • 101
  • sorry edited the stuff, AA should be A – Gabriel Jun 13 '14 at 18:34
  • Do you know what the `operator T*() const` line does? – Mooing Duck Jun 13 '14 at 18:34
  • I really don't understand your confusion here. This is doing exactly what I'd expect it to do. Are you expecting `gaga(A& a)` to get called on a pointer? I'm also not sure what you mean by "cast to reference". You don't cast to a reference, you just create a reference to something, or pass something by reference to get one. – tadman Jun 13 '14 at 18:35
  • obviously i dont know what `operator T*()` const does – Gabriel Jun 13 '14 at 18:39
  • So your question is ... why is the compiler doing exactly what I asked it to? – Praetorian Jun 13 '14 at 18:39
  • 1
    @Gabriel Read [this](https://stackoverflow.com/questions/4421706/operator-overloading). The part relevant to your question is [this](https://stackoverflow.com/a/16615725/241631) answer ... `operator T*()` is not the deference operator but a user defined conversion operator to implicitly convert a `B` to `A *` – Praetorian Jun 13 '14 at 18:42
  • No I dont understand what the compiler does here – Gabriel Jun 13 '14 at 18:42

1 Answers1

2

well, b is a of type B< A > b which can be cast to a T*, because of the conversion operator you added, meaning it can be cast to a A*.

when calling the dereference operator, you see that *b become A, so it is quite obvious that the second gaga is called, as it has a reference as parameter.

in the second case, it's even more obvious. You have a pointer to A, it will be matched with the only gaga function that takes a pointer as an argument, the first one.

Pinna_be
  • 4,517
  • 2
  • 18
  • 34