模板函数参数继承
template function parameter inheritance
我有一个调度程序,它可以返回任何类型,接受命令和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
。
相关文章:
- 为什么C++构造函数在继承中需要默认参数?
- C++接口继承不同的参数方法
- 如何在继承层次结构中调用具有默认参数的构造函数?
- 模板的继承参数设置
- 使用多参数包可变参数模板继承类
- 使用继承初始化C++中的参数
- 可变参数模板和具有继承的默认值
- 作为模板参数的成员函数指针在继承的成员函数上失败,如何以及为什么?
- 从作为模板参数传递给构造函数的类继承,或者从它们继承
- 在编译时检查未实例化的类模板是否继承自其第一个模板参数
- 继承基构造函数,基类是模板参数 (MSVC)
- C++ 函数的继承,传入参数
- C++ 模板元编程:从模板模板参数继承
- 类成员在继承的情况下用作模板参数
- C++中模板参数的类继承
- 继承专业化的模板参数推导
- 继承类模板的参数化构造函数
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- 具有可变模板的递归继承和继承参数问题
- 函数是否可以继承参数