模板函数参数继承

template function parameter inheritance

本文关键字:继承 参数 函数      更新时间:2023-10-16

我有一个调度程序,它可以返回任何类型,接受命令和FormData对象。这个想法是,我希望在传递特定内容时从 FormData 继承。

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;
}

我收到一个错误,说无法从表单转换为表单数据。我拿走了模板,一切正常(但我需要模板)

您的FormData类是基类,Form是派生的,但是您的登录函数看起来像

void login(const Form *f){}

但是在调度函数中,您正在尝试传递基类指针

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

C++根本不会让你这样做。 Form* 可以隐式转换为 FormData*,但不能反过来。

也许你可以向调度函数添加另一个模板参数,并让该函数在编译时找出具体类型:

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);
}

可以从Form*(派生类)隐式转换为FormData*(基类),但不能FormData*(基类)隐式转换为Form*(派生类)。

一旦你输入dispatch函数,编译器就知道你有一个指向基类FormData的指针;它不知道你正在传递一个指向派生类的指针,Form