在我的 FileProc 类中,我有四个函数:
ReadFile(TemplateList<char> &ReadList){}
ReadFile(TemplateListAdv<char> &ReadList){}
ReadFile(CharList &ReadList){}
ReadFile(CharListAdv &ReadList){}
它们都应该调用集中式方法(它们被转换为):
ReadFile(TemplateListEditor<char> &ReadList){} //Contained by FileBasic
对于背景信息,类层次结构如下:
TemplateList -> CharList
TemplateList -> TemplateListAdv
CharList -> CharListAdv
TemplateList -> TemplateListEditor
FileBasic -> FileProc
我的问题是有一个递归函数调用(其中 TemplateList 转换为 TemplateListEditor 将继续调用 TemplateList 函数),尽管类在内部是不同的。类型转换似乎不起作用。在不重命名函数的情况下(这会破坏重点,因为它应该是通用的),我如何使该方法查找正确的方法?
(令我惊讶的是,编译器从未为此标记出歧义解析错误)。
例子:
const bool ReadFile(TL::TemplateList<char> &ReadList, const bool Recursion = false)
{
printf("Is recursion true? %d!\n",Recursion);
TL::TemplateListEditor<char> Temp(ReadList);
//Calls itself instead of
//const bool ReadFile(TL::TemplateListEditor<char> &ReadList, const bool Recursion = false)
if(!ReadFile(static_cast<TL::TemplateListEditor<char> &>(Temp),true ))
{
return false;
}
return true;
}
以上将输出:
Is recursion true? 0
Is recursion true? 1
Is recursion true? 1
etc
令我震惊的是,TemplateListEditor(尽管是静态转换等)不知何故或出于某些令人难以置信的原因,被转换回 TemplateList。编辑器的构造函数都是显式的。
最佳答案
你的问题不是很清楚。但我假设你有这样的东西:
class A { ... };
class B : public A { ... };
void readFile(A &a) { ... };
void readFile(B &b)
{
readFile(b); // Recursive call
readFile(static_cast<A&>(b)); // Non-recursive call
}
函数重载是在编译时确定的,而不是运行时。编译器尝试根据参数的static 类型找到最佳匹配。
关于c++ - 子类递归方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7478604/