Overriding a C ++ function using a struct

Let's say "foo.hpp" contains the following. I have a function with the same name as the struct.

int foo(int i);

struct foo{
 foo(int i){ value = i;}
 operator int() {return value;}
 int value;
};

      

If I call it like this:

int main()
{
 std::cout << foo(1) << std::endl; // function is called, not the struct, why??
}

      

Why does the compiler always bind a function and not a struct? If possible, how to change that the structure is related and not the function?

Ultimately, I would like to overwrite the function in the library by adding an additional header file and overwriting the function with a structure. Thus, I hope to change one specific function, but continue to use all other library functions, but not change the library code at the same time.

+3


source to share


2 answers


Justification

According to C ++ standard N4431 ยง 3.3.10 / 2 Name hiding [basic.scope.hiding] ( emphasis mine ):

A class name (9.1) or an enumeration name (7.2) can be hidden by a variable name , data member , or an enumerator declared in the same scope. If a class or enumeration name and a variable, given member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable , data member, function, or enumerator name is visible.



Decision

Put either struct foo

or a function foo

in your own namespace

.

+11


source


There's a lot going on here.

When you have a function inside a struct that has the same name as a struct, it is a "constructor". It is called to populate the member variables of the structure. In your case, the constructor foo assigns the value "i" to the member variable "value".

Then basically you create a struct foo object, giving it a value of 1. In context, the compiler discovers that you have provided an int conversion operator that it uses to stream the object.



So, I'm not sure I understand how you think a struct should be bound instead of a function. You can call constructors to create objects. You cannot name a structure. (if you don't make the () operator in it, you can call that member function of the structure. But you haven't done any of them, so there is no point in "naming the structure".)

As far as overriding library functions - do you have access to the code you want to call your new function? It wouldn't be embarrassing to just change the call to a new function. If you need to change but cannot change the source, you can (often) provide a new function with EXACTLY the same signature in the same set of object modules, and it will be used before the linker finds a different version in the library. But what you want is a function, not a structure.

+1


source







All Articles