Thread: template parameter of base class is derived class

  1. #1
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937

    template parameter of base class is derived class

    When instantiating Singleton<>, how does the compiler know what constructors are available for class Updater? I'm referring to the bolded line.

    (This code is greatly reduced, but I see something just like it running around in the wild.)
    Code:
    template<typename SingletonClass>
    class Singleton
    {
        public:
            Singleton() {}
            static SingletonClass & instance();
        private:
            static auto_ptr<SingletonClass> ptr;
            // and the other constructors
    };
    
    template <typename SingletonClass>
    SingletonClass & Singleton<SingletonClass>::instance()
    {
        if (ptr.get() == 0)
            ptr.reset(new SingletonClass());
       
        return *ptr;      
    }
    
    // . . . 
    
    class Updater : public Singleton<Updater>
    {
        // constructors and methods and all that..
    };
    There is something that I do not understand about the order in which the compiler sees symbols. Thanks!
    Last edited by CodeMonkey; 12-29-2011 at 03:35 PM. Reason: error
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  2. #2
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    Apparently this is the "Curiously Recursive Template Pattern." A wiki is worth a thousand words...
    Last edited by CodeMonkey; 12-29-2011 at 03:40 PM.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    The rules for lookup can be complex at times, but it's pretty clear here that the intent is to call the constructor of the class that *this belongs to. And apparently the writers of the standard thought of this case, and made it work correctly.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 06-20-2008, 02:41 AM
  2. derived class can not access base class protected member?
    By George2 in forum C++ Programming
    Replies: 2
    Last Post: 10-21-2007, 06:32 PM
  3. finding derived class type of a pointer to a base class
    By LinuxCoder in forum C++ Programming
    Replies: 15
    Last Post: 04-10-2006, 11:08 AM
  4. Replies: 2
    Last Post: 04-06-2005, 07:25 AM
  5. Replies: 1
    Last Post: 12-11-2002, 10:31 PM