Help needed to understand "member function template"

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Aries Sun

    #1

    Help needed to understand "member function template"

    I am reading the book "Effective C++" Item 25 mentioned the following
    code:
    // a first cut at a class yielding NULL pointer objects
    class NullClass {
    public:
    template<class T // generates
    operator T*() const { return 0; } // operator T* for
    }; // all types T; each
    // function returns
    // the null pointer
    const NullClass NULL; // NULL is an object of
    // type NullClass
    void f(int x); // same as we originally had
    void f(string *p); // ditto
    f(NULL); // fine, converts NULL to
    // string*, then calls f(string*)
    I have a hard time to understand the above, can anybody explain it to
    me? thanks,

  • Aries Sun

    #2
    Re: Help needed to understand &quot;member function template&quot;

    my understanding is like this:
    compiler would try to find out the right function for call f(NULL),
    and will try f(int x), obviously this is not the right one, then will
    try f(string *P), but this definition needs pointer so compiler will
    try to call T* to do implicit conversion.

    Am i right? thanks

    Comment

    • Barry

      #3
      Re: Help needed to understand &quot;member function template&quot;

      Aries Sun wrote:
      my understanding is like this:
      compiler would try to find out the right function for call f(NULL),
      and will try f(int x), obviously this is not the right one, then will
      try f(string *P), but this definition needs pointer so compiler will
      try to call T* to do implicit conversion.
      >
      Am i right? thanks
      >
      you are right,
      First, it find the exact match, but fail,
      then find any other, to which NULL is convertible.

      BTW, don't use NULL as an variable name in the program other than demo,
      as it is a standard macro.

      --
      Thanks
      Barry

      Comment

      • Aries Sun

        #4
        Re: Help needed to understand &quot;member function template&quot;

        thanks!

        On Sep 22, 4:54 am, Barry <dhb2...@gmail. comwrote:
        Aries Sun wrote:
        my understanding is like this:
        compiler would try to find out the right function for call f(NULL),
        and will try f(int x), obviously this is not the right one, then will
        try f(string *P), but this definition needs pointer so compiler will
        try to call T* to do implicit conversion.
        >
        Am i right? thanks
        >
        you are right,
        First, it find the exact match, but fail,
        then find any other, to which NULL is convertible.
        >
        BTW, don't use NULL as an variable name in the program other than demo,
        as it is a standard macro.
        >
        --
        Thanks
        Barry

        Comment

        Working...