开发者

forward declare derived class from template c++

I am having trouble working out some kinks in a design implementation. It goes something like this:

I have a template base class which has a conversion method.

// Foo.h

class Bar;

template<typename T>
class Foo {

    virtual const Bar toBar();

}

I want a derived class Bar to inherit from a specific form of Foo for example:

// Bar.h
class Bar : public Foo<float> {
    // Insert Bar methods here, Etc.
}

As Foo is a template the implementation has to be fully defined in the header, this causes the problem that the implementation of the method toBar() will need to be able to create an instance of type Bar. So that tells me I need to include the Bar.h header file after the Foo definition but before the Foo implementation.

However, in Bar.h the class Bar is derived from Foo so a full definition of Foo must be provided. This causes problems because the two files have a cyclic dependency that cannot be solved via forward declarations because the forward declaration is a derived class.

This get even more complicated if another class SomeClass has a data member of开发者_StackOverflow社区 type Bar as this required including the Bar.h which includes the Foo.h which (because it is a template) includes Bar.h.

Oh and just to be clear all the header files have inclusion guards using

#ifndef _HEADER_NAME_H_
#define _HEADER_NAME_H_
...
#endif

How have other people solved complex issues like this?

As a more concrete example say I have an Array class that has a method to convert it to a human readable String class such as toString()...however the String class is declared as being as

class String : public Array<char> {...};

Thanks in advance. Gary.


In order for Foo< float > to be a base class, it must have been fully defined by the point of Bar definition. However, Foo doesn't necesarily need to know about Bar, if you could make Bar be a dependent typename within Foo.

A forward declaration of Bar before defining Foo may be enough. If you post/link more concrete code, I may be able to give you a better answer.

Try this:

class Bar;

template< typename T, typename DependantBar = Bar >
class Foo {

    virtual const DependantBar toBar();

}


class Bar : public Foo<float> {
    template <typename T>
    Bar create(const Foo<T>&);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜