Thread: Linking error with static template class members

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    271
    After some googling and tinkering, I've found a solution, but I can't say I understand why it works.

    Code:
    // in a header file
    template <typename T>
    class A {
    static stl_container<T*>* container;
    };
    
    //you need a second declaration outside the body of the class
    //in the header
    template <typename T>
    typename A<T>::stl_container<T*>* container;
    Why you need the second declaration is beyond me. But it works.

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Why is that so surprising? You have to do that even without templates.

    Code:
    class A
    {
    public:
        static int x;
    };
    
    int A::x;
    
    int main()
    {
        A::x = 0;
        return 0;
    }
    How could it be otherwise? How does the compiler magically decide which .cpp module the definition of the static member should come from? The "static int x" is only a declaration -- you still need to define the variable in some specific .cpp module.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. LNK2001 ERROR!!! need help
    By lifeafterdeath in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2008, 05:05 PM
  2. template function v.s. template class
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 12-13-2007, 01:46 AM
  3. error: template with C linkage
    By michaels-r in forum C++ Programming
    Replies: 3
    Last Post: 05-17-2006, 08:11 AM
  4. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM
  5. bug for static functions in template class
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 09-16-2001, 06:38 PM