Search code examples
c++templatesforward-declarationvisitor-pattern

Forward Declaration of Template Class (Visitor Design Pattern)


I am trying to forward declare a templated class A<T> for use in a class Visitor. It would suffice for my purposes to declare the int instance A<int> of the class A. I have tried two approaches but both give different errors, and I don't know how to proceed.

Here is a MWE of my error:

namespace visitor{  
    class Visitor{
    public:
        virtual void visit(nsp::A<int>*) = 0;
    };    
}

namespace nsp{    
    template <class T>
    class A{
        A();
        T t_attribute;          
        void accept(visitor::Visitor*);
    };    

    void A<int>::accept(visitor::Visitor*){
        v -> visit(this);
    }        
}

int main(){
    return 0;
}

You can try running the code here to see the error I get:

error: specializing member 'nsp::A<int>::accept' requires 'template<>' syntax

I appreciate any help.


Solution

  • I think you are mixing things here, you should declare accept method as:

    template<class T>
    void A<T>::accept(visitor::Visitor* v){
        v -> visit(this);
    }
    

    as class A is template. Then you can specialize for any type.