How to modify a function behaviour without template method? - c++

I have a function (actually from ATL, it is ATL::CSoapMSXMLInetClient::SendRequest(LPCTSTR)) whose behaviour should slightly be modified. That is, I just have to add one function call somewhere in the middle of the function.
Taking into consideration that this is not a template method, what is the best practice of changing its behaviour? Do I have to re-write the whole function?
Thanks in advance.
EDIT: Deriving from the class ATL::CSoapMSXMLInetClient and copy-pasting whole function code with a slight modification in subclass function definition does not work because most of the members used in ATL::CSoapMSXMLInetClient::SendRequest are "private" and accessing them in subclass is a compile time error.
Rather than best practice I am looking for a way to do it now, if there is any. :(

Yes you will. If it's in the middle of the function there is no way of getting around it.

There are some refactoring methods you can use. But I cannot think of any pretty ones, and all depend heavily on the code within the class, although for you case it might be tough to find any that works.
Like if you have a line:
do_frobnicate();
dingbat->pling();
And you need to call somefunc() after the dingbat plings. You can, if the dingbat is an interface that you provide, make a new dingbat that also do somefunc() when it plings. Given that the only place this dingbat plings is in this function.
Also, if do_frobnicate() is a free function and you want to add the somefunc() after this, you could create a function within the class, or within its namespace that is called the same. That way you make your own do_frobnicate() that also does somefunc().

Related

Lazy evaluation for subset of class methods

I'm looking to make a general, lazy evaluation-esque procedure to streamline my code.
Right now, I have the ability to speed up the execution of mathematical functions - provided that I pre-process it by calling another method first. More concretely, given a function of the type:
const Eigen::MatrixXd<double, -1, -1> function_name(const Eigen::MatrixXd<double, -1, -1>& input)
I can pass this into another function, g, which will produce a new version of function_name g_p, which can be executed faster.
I would like to abstract all this busy-work away from the end-user. Ideally, I'd like to make a class such that when any function f matching function_name's method signature is called on any input (say, x), the following happens instead:
The class checks if f has been called before.
If it hasn't, it calls g(f), followed by g_p(x).
If it has, it just calls g_p(x)
This is tricky for two reasons. The first, is I don't know how to get a reference to the current method, or if that's even possible, and pass it to g. There might be a way around this, but passing one function to the other would be simplest/cleanest for me.
The second bigger issue is how to force the calls to g. I have read about the execute around pattern, which almost works for this purpose - except that, unless I'm understanding it wrong, it would be impossible to reference f in the surrounding function calls.
Is there any way to cleanly implement my dream class? I ideally want to eventually generalize beyond the type of function_name (perhaps with templates), but can take this one step at a time. I am also open to other solution to get the same functionality.
I don't think a "perfect" solution is possible in C++, for the following reasons.
If the calling site says:
result = object->f(x);
as compiled this will call into the unoptimized version. At this point you're pretty much hamstrung, since there's no way in C++ to change where a function call goes, that's determined at compile-time for static linkage, and at runtime via vtable lookup for virtual (dynamic) linkage. Whatever the case, it's not something you can directly alter. Other languages do allow this, e.g. Lua, and rather ironically C++'s great-grandfather BCPL also permits it. However C++ doesn't.
TL;DR to get a workable solution to this, you need to modify either the called function, or every calling site that uses one of these.
Long answer: you'll need to do one of two things. You can either offload the problem to the called class and make all functions look something like this:
const <return_type> myclass:f(x)
{
static auto unoptimized = [](x) -> <return_type>
{
// Do the optimizable heavy lifting here;
return whatever;
};
static auto optimized = g(unoptimized);
return optimized(x);
}
However I very strongly suspect this is exactly what you don't want to do, because assuming the end-user you're talking about is the author of the class, this fails your requirement to offload this from the end-user.
However, you can also solve it by using a template, but that requires modification to every place you call one of these. In essence you encapsulate the above logic in a template function, replacing unoptimized with the bare class member, and leaving most everything else alone. Then you just call the template function at the calling site, and it should work.
This does have the advantage of a relatively small change at the calling site:
result = object->f(x);
becomes either:
result = optimize(object->f, x);
or:
result = optimize(object->f)(x);
depending on how you set the optimize template up. It also has the advantage of no changes at all to the class.
So I guess it comes down to where you wan't to make the changes.
Yet another choice. Would it be an option to take the class as authored by the end user, and pass the cpp and h files through a custom pre-processor? That could go through the class and automatically make the changes outlined above, which then yields the advantage of no change needed at the calling site.

Needing a private and public method for the same recursive function

We have recently been working on implementing recursive methods for several classes (trees, heaps, queues, linked lists, etc) in C++ for my computer science class. I have not been having any trouble writing the implementations for the methods, but something my professor mentioned briefly in passing confused me and she never elaborated on the point.
She mentioned that when implementing a recursive function for a class you need to have both a public and private version of that function.
For example (part of a linked list class definition):
public:
// constructors, destructors
// member functions etc.
findMax() { findMax(head); }
private:
findMax(Node* first_node) { // actual code with recursive calls }
Node* head;
So here there are two functions, one private and one public. All the public function does is call the private function and return whatever it finds to be the answer.
I have a few questions about this.
Is this something you must do?
Does this only apply to class methods that are recursive? If so, what about recursive functions makes this necessary? Would you do this for other functions?
My intuition is that perhaps this is done to ensure that people using the public class methods don't go full dingus mode and end up calling a recursive function with parameters that won't ever lead to a stopping/base case.
Can anyone elaborate on this idea in general and explain it in an intuitive way?
Thanks!
EDIT: Thank you all for your quick answers they have been very helpful! I think I may have misheard my professor and this actually has nothing to do with recursion (though the example she was writing may have been) and is rather just a convention in Object Oriented Programming.
The idea within OOP being that findMax() requires the use of a private class variable (head) to be of use, but would be a handy public function. The private version of findMax(Node* n) then allows a public user to find the max of the list without having the opportunity to access and mess up the private head.
Thanks everyone! Cheers.
"My intuition is that perhaps this is done to ensure that people using the public class methods don't go full dingus mode and end up calling a recursive function with parameters that won't ever lead to a stopping/base case."
Your intuition is right up to some point. head is managed internally with the class, and shouldn't be introduced as a parameter from a caller.
There's no specific relevance to recursion, but rather data encapsulation OOP principles:
head should be managed from the class internally, though a function findMax() should be available in the public class interface. To provide an appropriate internal implementation the search is delegated to a private implementation, which in this case is used recursively. But that doesn't really matter as mentioned.
As for your edits in the question. You should put as much code as possible into the private function, and leave it narrow. I can't see any reason, why your prof put these in the public function.
Is this something you must do?
No.
Does this only apply to class methods that are recursive?
Not even that.
If so, what about recursive functions makes this necessary?
Nothing.
Would you do this for other functions?
Yes, I would. It's a choice you make about organising your code. In general, the functions invoked by my public class member functions are private, unless there's any inherent need for them to also be public.
She mentioned that when implementing a recursive function for a class you need to have both a public and private version of that function.
Assuming this is close to verbatim, your teacher was either wrong or unclear. (It's also possible that she was leaving the element of "choice" for a future lesson; whether this is ethical/reasonable or not is up for debate.)
One might also argue that, in this case, she misled you by giving the two findMax overloads the same name; findMax() and findMax(Head*) are two separate functions and you could have (I would have) called the latter findMaxImpl(Head*), or something like that. Then you will see that recursion doesn't have anything to do with this.
My intuition is that perhaps this is done to ensure that people using the public class methods don't go full dingus mode and end up calling a recursive function with parameters that won't ever lead to a stopping/base case.
Amusingly, your intuition is a lot more sensible here than C++ actually is. :P There is nothing in the language to prevent or even try to prevent "full dingus mode". Not really.

Force error (compile time) if anyone calls a method in C++

DISCLAIMER: CCNode class is part of the cocos2d-x framework, which i didn't desing.
Base class CCNode has a init method:
virtual bool init();
My derived class needs two arguments, so I declare a new init method:
virtual bool init(int, int);
I'd like to enforce the use of the new init(int a, int) instead of the original one.
I know I have the option to call the new one with default parameters, but it doesn't feel right in the context.
I'm searching for a way to tell the user "Call init(int, int) instead" if anyone tries to call that one. I'd rather get that at compile time that at runtime.
I've tried C++11's static_assert(false, "message"), but fails without calling it...
If your really want to prevent someone calling the standard node method I think you should inherit it privately. However, the more cocosy way of doing this would simply be to call the new init from your create method, which is the only one that should be called by outside code when constructing your object anyway.
Sounds like you have source code access, since you tried sticking a static assert in there? The only way I think you can do exactly what you want is to templatize the function in question. Placing a static assert in a templatize function is a good way to ensure it doesn't compile.
Another option would be to hide the declaration in the private section of your class.
Lastly, a run-time assertion is the most common way I ever achieve what you're asking to do.
If you don't have source code access to that init function, then I really don't think you can do what you're asking.

Change the address of a member function in C++

in C++, I can easily create a function pointer by taking the address of a member function. However, is it possible to change the address of that local function?
I.e. say I have funcA() and funcB() in the same class, defined differently. I'm looking to change the address of funcA() to that of funcB(), such that at run time calling funcA() actually results in a call to funcB(). I know this is ugly, but I need to do this, thanks!
EDIT----------
Background on what I'm trying to do:
I'm hoping to implement unit tests for an existing code base, some of the methods in the base class which all of my modules are inheriting from are non-virtual. I'm not allowed to edit any production code. I can fiddle with the build process and substitute in a base class with the relevant methods set to virtual but I thought I'd rather use a hack like this (which I thought was possible).
Also, I'm interested in the topic out of technical curiosity, as through the process of trying to hack around this problem I'm learning quite a bit about how things such as code generation & function look-up work under the hood, which I haven't had a chance to learn in school having just finished 2nd year of university. I'm not sure as to I'll ever be taught such things in school as I'm in a computer engineering program rather than CS.
Back on topic
The the method funcA() and funcB() do indeed have the same signature, so the problem is that I can only get the address of a function using the & operator? Would I be correct in saying that I can't change the address of the function, or swap out the contents at that address without corrupting portions of memory? Would DLL injection be a good approach for a situation like this if the functions are exported to a dll?
No. Functions are compiled into the executable, and their address is fixed throughout the life-time of the program.
The closest thing is virtual functions. Give us an example of what you're trying to accomplish, I promise there's a better way.
It cannot be done the way you describe it. The only way to change the target for a statically bound call is by modifying the actual executable code of your program. C++ language has no features that could accomplish that.
If you want function calls to be resolved at run-time you have to either use explicitly indirect calls (call through function pointers), or use language features that are based on run-time call resolution (like virtual functions), or you can use plain branching with good-old if or switch. Which is more appropriate in your case depends on your specific problem.
Technically it might be possible for virtual functions by modifying the vtable of the type, but you most certainly cannot do it without violating the standard (causing Undefined Behavior) and it would require knowledge of how your specific compiler handles vtables.
For other functions it is not possible because the addresses of the functions are directly written to program code, which is generally on a read-only memory area.
I am fairly sure this is impossible in pure C++. C++ is not a dynamic language.
What you want is a pointer to a function, you can point it to FuncA or FuncB assuming that they have the same signature.
You cannot do what you want to do directly. However, you can achieve a similar result with some slightly different criteria, using something you are already familiar with -- function pointers. Consider:
// This type could be whatever you need, including a member function pointer type.
typedef void (*FunctionPointer)();
struct T {
FunctionPointer Function;
};
Now you can set the Function member on any given T instance, and call it. This is about as close as you can reasonably get, and I presume that since you are already aware of function pointers you're already aware of this solution.
Why don't you edit your question with a more complete description of the problem you're trying to solve? As it stands it really sounds like you're trying to do something horrible.
Its simple!
For
at run time calling funcA() actually results in a call to funcB().
write funcA() similar to following:
int funcA( int a, int b) {
return funcB( a, b );
}
:-)

Run Code Before Every Function Call for a Class in C++

I would like to run some code (perhaps a function) right before every function call for a class and all functions of the classes that inherit from that class. I'd like to do this without actually editing every function, Is such a thing even possible?
I would settle for having a function called as the first instruction of every function call instead of it being called right before.
AspectC++ is what you want. I haven't used it myself, but Aspect-Oriented Programming paradigm tries to solve this exact problem.
I would suggest using the Non Virtual Interface idiom. All public functions are non-virtual. All virtual functions are protected or private. Public members delegate the calls to virtual members and are usually implemented as inline functions.
This is the way IOStreams are implemented in STL. You can read more about it at C++ Wikibooks.
Intent: To modularize/refactor common before and after code fragments (e.g., invariant checking, acquiring/releasing locks) for an entire class hierarchy at one location.
Regards,
Ovanes
The following might be a bit of an overkill - but how about?
http://msdn.microsoft.com/en-us/library/c63a9b7h.aspx
Another thing you could consider is using something like the [boost/C++0X] shared_ptr wrapper, where you call your custom function on the '->' overload before returning the class instance pointer. It involves modifying usage but not the underlying class, and I've used it a couple times to achieve the same effect. Just another thought.
The somewhat inconvenient way where to build a wrapper class that takes an object of your base type and calls the surrounding function and then the function that you wanted to call. This would be something like a decorator.
The best you can do is to declare a set of virtual functions as protected and have the developers inheriting from the class override the virtual functions. The interface used by the base class can be public, which executes the desired code before passing information to the protected virtual method.
For example:
class Base {
public:
void MyMethod(void) { /* Insert code here */ YourMethod(); }
protected:
virtual void YourMethod(void) {}
};
If the developer knows that he has a specific subclass, he can still bypass your code simply by using a dynamic_cast, and using his own method set. As such, you may want to follow the other suggestions already posted that do not involve the base C++ language.
This sounds like what a profiler does. Have you looked at the source for any profiling tools?
You could also do this with the Curiously recurring template pattern (CRTP).
Using g++, you could use the option -pg for the respective compilation units, which makes the compiler generate a call to the function mcount at the start of every function. mcount is usually provided by profiling tools like gprof, but you can also implement it yourself. You should however make sure that
mcount has C linkage (and is not C++-style name-mangled), i.e. by implementing it as a C function and compiling with a pure C compiler like gcc.
the compilation unit containing mcount is not compiled with -pg.