Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declarations: templates and inheritance

When writing a framework I got following problem: I have class A and class B wchich is derived from class A.

class A has a function wchich returns B*.

Of course, it's not difficult:

#include <iostream>
using namespace std;

class B; // forward declaration

class A
{
    public:
        B* ReturnSomeData();
};

class B : public A
{
};

// Implementation:

B* A::ReturnSomeData()
{
    return new B; // doesn't matter how the function makes pointer
}

int main()
{
    A sth;

    cout << sth.ReturnSomeData(); // print adress
}

However I had to use templates like here:

#include <iostream>
using namespace std;

// This "forward declaration":

template <class Number>
class B<Number>;

// cannot be compiled:
// "7 error: 'B' is not a template"

template <class Number>
class A
{
    public:
        B<Number>* ReturnSomeData();
};

template <class Number>
class B : public A<Number>
{
};

// Implementation:

template <class Number>
B<Number>* A<Number>::ReturnSomeData()
{
    return new B<Number>;
}

int main()
{
    A<int> sth;

    cout << sth.ReturnSomeData();
}

Look at the code. As you can see I don't know how to deal with unknown by A B*. Is it possible to write forward declaration? Or I need something different?

Yes, I searched and I see there are many posts about template declarations but can't find solve for my individual problem. It's a bit complex for me.

Thanks for help.

like image 712
leuays Avatar asked Jan 20 '23 19:01

leuays


1 Answers

Your forward declaration is incorrect. It needs to be:

template <class Number>
class B;
       ^ no argument list
like image 78
James McNellis Avatar answered Jan 22 '23 10:01

James McNellis