Template function inheritance

I have a dispatcher that can return any type, accepts a command and a FormData object. The idea is that I want to inherit from FormData when passing through certain material.

struct FormData {};

struct Form : FormData {};

void login(const Form *f){}

enum Command
{
    LOGIN
};

template <typename T>
T dispatch(const Command command, const FormData *f)
{
    switch (command)
    {
    case LOGIN: login(f);
    }

    return T();
}

int main()
{
    Form f;

    dispatch<void>(LOGIN, &f);

    return 0;
}

I get an error that cannot convert from Form to FormData. I take the template, everything works fine (but I need a template)

+3
source share
2 answers

Your class FormDatais the base class Formreceived, however your login function looks like

void login(const Form *f){}

But in your submit function you are trying to pass a base class pointer

T dispatch(const Command command, const FormData *f)
{
    switch (command)
    {
    case LOGIN: login(f);
    }

C ++ just won't let you do this. Form * can be implicitly converted to FormData *, but not vice versa.

, :

struct FormData {};

struct Form : public FormData {};

void login(const Form *f){}

enum Command
{
    LOGIN
};    

template <typename T>
T dispatch(const Command command)
{
    return T();
}

template <typename T, typename FormDataType>
T dispatch(const Command command, const FormDataType *f)
{
    switch (command)
    {
    case LOGIN: login(f);
    }

    return dispatch(command);
}

int main()
{
    Form f;

    dispatch<void>(LOGIN, &f);
    dispatch<void>(LOGIN);
}
+2

Form* ( ) FormData* ( ), FormData* ( ) Form* ( ).

dispatch, , FormData; , , Form.

+1

All Articles