Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

c++ - Is it possible to bring global function into the overload resolution with member function?

Here is the corresponding question, what I want to know is, Is it possible to bring global function into the overload resolution with member function?

I tried in 2 ways, but both don't work:

void foo(double val) { cout << "double
";}

class obj {
public:
  using ::foo; // (1) compile error: using-declaration for non-member at class scope
  void callFoo() { 
    using ::foo; // (2)will cause the global version always be called
    foo(6.4); 
    foo(0); 
  }
private:
  void foo(int val) {cout << "class member foo
"; }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I doubt you can make the compiler call one or the other based on the type. You can of course use a local wrapper function, something like this:

  void callFoo() { 
    foo(6.4); 
    foo(0); 
  }
private:
  void foo(double val) { ::foo(val); }

The wrapper function should nicely inline into nothing, so there is no actual overhead when compiled with optimisation.

Or don't call the member and the global function the same name, which makes life a whole lot easier!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...