Search code examples
c++templatesforward-declaration

Forward Declare instance of Template Class with Virtual Functions


I have created a template class A<T> in mynamespace which I need to forward declare to use in class B in mynamespace2. Is it possible to forward declare a specific instance of A for use in B, namely A<int>?

File: a.h

#include "b.h"

namespace mynamespace{    
    template <class T>
    class A{
        A(T);                                // constructor
        mynamespace2::B* b_attribute;
    };    
}

File: b.h

/* How to forward declare A<int>? This doesn't work:
 *
 *  namespace mynamespace{
 *     class A<int>;
 *  }
 * 
 * neither does this:
 *
 * namespace mynamespace{
 *     template <class T>
 *     class A<T>
 * }
 */

namespace mynamespace2{    
    class B{
        B();
        mynamespace::A<int>* a_attribute;    // for use over here
        virtual void f(A<int>*);             // note: virtual function
    };    
}

I appreciate any help.


Solution

  • This is no different than forward-declaring anything else, except that you have to get the namespace right:

    namespace mynamespace{    
        template <class T> class A;
    }
    

    A is declared in mynamespace, so you have to specify it, as such.

    If you really want to avoid explicitly specifying the namespace every time, add a using declaration:

    namespace mynamespace2{
        using mynamespace::A;
    
        class B{
            B();
            A<int>* a_attribute;    // for use over here
        };    
    }
    

    Once a using declaration is made, you can just refer to A anywhere within mynamespace2.

    Note that you must still forward-declare the template in the other namespace, before pulling it in with using.