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 func开发者_JS百科tion 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.
Your forward declaration is incorrect. It needs to be:
template <class Number>
class B;
^ no argument list
精彩评论