samedi 15 décembre 2018

As Virtual on Member variables in inheritance class

I did a small exemple to try to explain you with my poor english what I want to do :).

I have a main class who is my engine. This is my parent class of several children.

this is the parent class :

#include <string>
#include <iostream>
#include <vector>

template <typename Type> class A
{
    public:
                            A(std::string const &str) :
                m_str(str)
        {
        }
        void                run(void) const
        {
            unsigned int    i;

            for(i = 0; ACTIONS[i].f != nullptr; i++)
                if (m_str == ACTIONS[i].key)
                    return ((*(this).*ACTIONS[i].f)(m_str));
        }
    protected:
        typedef struct      s_action
        {
            std::string     key;
            void            (Type::*f)(std::string const &);
        }                   t_action;
        static t_action const
                            ACTIONS[];
        std::string         m_str;
};


class B : public A<B>
{
    public:
                            B(std::string const &str);
    protected:
        static t_action const
                            ACTIONS[];
        void                error(std::string const &str);
        void                success(std::string const &str);
};

I would like to call children method with table pointer of member function in this parent class A::run as you can see above

This code does not compile.

I know it's not possible to have a static variable virtual, but it's exactly that I need to do have for A::ACTIONS. I absolutely need to initialise B::ACTIONS to A::run works.

In first Is it possible? Have you got a small exemple of this case?

This is the end of my small code :

#include "Class.hpp"

B::t_action const               B::ACTIONS[] = {
    {"ERROR", &B::error},
    {"SUCCESS", &B::success},
    {"", nullptr}
};

                            B::B(std::string const &str) :
        A<B>(str)
{
}

void                        B::error(std::string const &str)
{
    std::cerr << str << std::endl;
}

void                        B::success(std::string const &str)
{
    std::cout << str <<std::endl;
}

And the main:

#include "Class.hpp"

int                         main(void)
{
    B                       b("SUCCESS");
    b.run();
    return (0);
}

I didn't try, normally this code should Display SUCCESS on stdout

Thank you for your help

Aucun commentaire:

Enregistrer un commentaire