开发者

Subclass recursive method call

In my FileProc class, I have four functions:

ReadFile(TemplateList<char> &ReadList){}
ReadFile(TemplateListAdv<char> &ReadList){}
ReadFile(CharList &ReadList){}
ReadFile(CharListAdv &ReadList){}

Which are all supposed to call a centralised method (which they are converted to):

ReadFile(TemplateListEditor<char> &ReadList){} //Contained by FileBasic

For background information, class hierarchy is as follows:

TemplateList -> CharList

TemplateList -> TemplateListAdv

CharList -> CharListAdv

TemplateList -> TemplateListEditor

FileBasic -> FileProc

My issue is there is a recursive function call (where TemplateList converted into TemplateListEditor will keep calling the TemplateList function), despite the fact the classes are internally different. Typecasting does not seem to work. Without renaming the function (which would defeat the point as it's supposed to be universal), how do I make the method look up the correct method?

(And I am surprised the compiler never flagged up an ambiguity resolution error for this).

Example:

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 开发者_StackOverflow中文版ReadFile(TL::TemplateListEditor<char> &ReadList, const bool Recursion = false)
    if(!ReadFile(static_cast<TL::TemplateListEditor<char> &>(Temp),true ))
    {
        return false;
    }
    return true;
}

The above will ouput:

Is recursion true? 0

Is recursion true? 1

Is recursion true? 1

etc

It strikes me TemplateListEditor (despite being static cast etc etc) is somehow or for some mind boggling reason, being converted back to TemplateList. Editor's constructors are all explicit.


Your question isn't very clear. But I'm assuming you have something like this:

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
}

Function overloads are determined at compile-time, not run-time. The compiler attempts to locate the best match based on the static types of the arguments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜