Related to Polymorphism/Templates

I have a parent_class which has a lot of child_class(es). The parent_class defines a function void generate() = 0; which is defined by all the child classes.

I have another class called "Generator" which has a pointer-to-parent_class constructor. The "Generator" class makes use of the generate() function.

Here's the problem. The child_classes take different arguments (a single object as argument) for generate();

So maybe we could template void generate(); like so:
virtual void generate(T) { }

full declaration:
1
2
3
4
5
6
7
8
9
10
template <typename T>

class parent_class {
public:
	virtual ~parent_class() { }
	parent_class() { }

	virtual void generate(T) { }

};


Generator class becomes:
1
2
3
4
template <typename T>
class Generator {
	Generator(parent_class<T>* obj) { }
};


But I don't want to write parent_class<T> because then Generator would then have to be instantiated with a type as well, which I want to avoid. For convenience sake.

(It's guaranteed that the Generator class will know what to call the generator() with.)

The only other way I could think of was to manually write all overloads of generate(), but that's tedious when you are expecting to add more child classes.
Last edited on
This is one (fairly simple) approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <typeinfo>

struct base
{
    virtual ~base() = default ;
};

template < typename T > struct A : base
{ virtual void generate( const T& ) = 0 ; };

template < typename T > struct derived : A<T>
{ virtual void generate( const T& )
  { std::cout << "derived<" << typeid(T).name() << ">::generate()\n" ; } };

struct generator
{
    base& b ;
    explicit generator( base& b ) : b(b) {}

    template < typename T > void generate( const T& v )
    {
        try { dynamic_cast< A<T>& >(b).generate(v) ; }
        catch( const std::bad_cast& ) { std::cout << "*** error: bad type\n" ; }
    }
};

int main()
{
    {
        derived<int> d ;
        generator g(d) ;
        g.generate(23) ; // derived<int>::generate
    }

    {
        derived<std::ostream> d ;
        generator g(d) ;
        g.generate(std::cout) ; // derived<std::ostream>::generate

        g.generate(23) ; // *** error: bad type
    }
}

https://rextester.com/LQR98481
Thanks JLBorges
edit: JLBorges your example helped me even more than I anticipated. Thanks ;)
Last edited on
Topic archived. No new replies allowed.