Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\n";}

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\n"; }
};
like image 397
songyuanyao Avatar asked Sep 16 '14 07:09

songyuanyao


People also ask

Can global member function be overloaded?

It is possible to overload an operator as a global, non-friend function, but such a function requiring access to a class's private or protected data would need to use set or get functions provided in that class's public interface.

Can we overload global function C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. Operator overloading involving vector types is not supported.

Can member functions be overloaded?

Function declarations that differ only by its return type cannot be overloaded with function overloading process. Member function declarations with the same parameters or the same name types cannot be overloaded if any one of them is declared as a static member function.

Can we overload member functions in oops?

Function Overloading in C++Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.


1 Answers

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!

like image 96
Mats Petersson Avatar answered Sep 21 '22 10:09

Mats Petersson