tags:

views:

46

answers:

4

Say I have the following:

template <class T>
class Foo {};

and a descendant class,

class Bar : public Foo<some_typename>{};

How would I go about passing Bar to Foo's constructor without Foo.h including Bar.h, if that is even possible?

A: 

What do you want to pass? A Bar or a Bar* or Bar&?

nakiya
aperson
A: 

You may be looking for:

template <typename T>
struct Foo
{
    Foo(const T& x) { }
};

struct Bar : Foo<Bar> { };
James McNellis
A: 

it's unusual, but there often ways around it, depending on your needs (elaborate, perhaps?).

understand that it only makes sense to pass another Bar to a Foo.

in this case, you could:

1) create a second template parameter in Foo and lay out the interface required at construction:

template < typename T, typename Bar_ >
class Foo {
   /* ... */
   Foo(Bar_& bar) : weight_(bar.getWeight()) {
   }
   /* ... */

2) or just use a template ctor:

template < typename Bar_ >
Foo(Bar_& bar) : weight_(bar.getWeight()) {
}

3) if Foo+Bar is lightweight, you could just create an extended initialization list, used by the Bar at init.

4) since it is a template (and the implementation must be visible to its subclass and has special linkage), you could also declare a Foo ctor which takes a Bar by pointer, then just define the Foo constructor in Bar.hpp

Justin
A: 

You seem to be looking for the "Curiously recurring template pattern" (CRTP).

Bart van Ingen Schenau