How to access to a template child method from a parent class?

I have a base class from which a template class inherits:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Base
{
    public :
        virtual ~Base() { };
        virtual void Print() const = 0;

        //This function is supposed to access Value() function in the Child class
        /*something*/ GetChildValue() const;
};

template< typename T >
class Child : public Base
{
    protected :
        const T* value;

    public :
        Child( const T* value ) : value( value ) { }
        ~Child() { }

        T Value() { return *value; }
        void Print() const { std::cout << *value << "\n"; }
};

The problem is I don't know how to define member function GetChildValue() in the Base class. So how?

NOTE: std::variant is not an option.
Last edited on
The return type of a function must be known at compile time. Unless you make it return some type of wrapper (such as std::any) you will not be able to return the value without the caller knowing what type he wants to be returned.

If you make GetChildValue() a function template you could let the caller pass the type that he wants as a template argument and then use dynamic_cast to convert the Base into the correct Child type so that you can call the correct Value() function.

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
44
#include <iostream>

class Base
{
    public :
        virtual ~Base() { };
        virtual void Print() const = 0;

        template <class T>
        T GetChildValue() const;
};

template< typename T >
class Child : public Base
{
    protected :
        const T* value;

    public :
        Child( const T* value ) : value( value ) { }
        ~Child() { }

        T Value() const { return *value; }
        void Print() const { std::cout << *value << "\n"; }
};

template <class T>
T Base::GetChildValue() const
{
    auto& child = dynamic_cast<const Child<T>&>(*this);
    return child.Value();
}

int main()
{
    int i = 123;
    Base* b = new Child<int>(&i);

    // OK, prints 123.
    std::cout << b->GetChildValue<int>() << '\n';

    // Error, throws a std::bad_cast exception.
    std::cout << b->GetChildValue<bool>() << '\n';
}
Last edited on
Topic archived. No new replies allowed.