I have a dispatcher which can return any type, takes a command, and a FormData object. The idea is that I wish to inherit from FormData when passing around specific stuff.
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 saying cannot convert from Form to FormData. I take away the template, everything works fine (but I need the template)
Your FormData class is the base class, Form is derived, however your login function looks like
void login(const Form *f){}
But in your dispatch 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++ simply won't let you do that. Form* can be implicitly converted to a FormData*, but not the other way around.
Perhaps you could add another template parameter to the dispatch function, and let that function figure out the concrete type at compile time:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With