简体   繁体   中英

How to call a static method member of a class when there is member method of the same name?

I have a class foo with two methods:

static void BuildToto(...);
void BuildToto(...);

The two methods have exactly the same prototype except that one is static while the other is not.

In a third method of the same class, I want to call the static method and not the other one. So, naively, I wrote this:

foo::BuildToto();

But while debugging, it becomes clear the code executes like the pointer this was present in the line above. How can I call the static method explicitly?

You can't: overload resolution will fail as no syntax can be employed to distinguish them.

One way around it, other than renaming one of the functions, would be to templatise one of the functions:

#include <iostream>
using namespace std;

struct Foo
{
    template<typename> void foo(int n) const {
        std::cout << "member\n";
    };
    static void foo(int n){
        std::cout << "static\n";
    }
};

int main() {        
    Foo::foo(1); // static
    Foo f;
    f.foo<void>(1); // member       
}

ok, i solve the mystery:

My two methods haven't the same exact prototypes except one has a vector among its input while the other one has a smart_pointer on vector. Unfortunately, i call the wrong version by not dereferencing the sp. So there was no compiler error. The fact the two methods share the same name and almost the same prototype just drove to my issue.

So i will take care to add a little suffixe to the static version of the methods to avoid any future confusion... Any idea for a suffixe to the static method's name?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM