Overloading methods with similar signatures - overloading

I am in a situation where i need to have two overloads for a method that should look like this,
void myMethod(string myParam)
{
// Some code to process myParam
}
void myMethod(string otherParam)
{
// Another code to process otherParam
}
Unfortunately C# compiler doesn't allow this kind of overloading, because it considers the two overloads to be having the same signature, it doesnt really matter if you are going to have different names for the paramters to represent different meanings.
I wonder how should i handle this kind of situation?

You maybe should create a class wich will extends this one and then you can overload your method.

Related

Extending a general purpose function

I'm creating a game, and in this game a ball can be caught in various ways, which all result in different behaviour. Initially, I wanted to add an enum to a certain general purpose method when catching to ball, which will then delegate the actions that take place when a ball gets caught in a certain way. An example would be:
void Weapon::Catch(Character Catcher, CatchMethod Method)
{
switch (Method)
{
case Method::PickUp: OnPickup(Catcher); break;
case Method::Pass: OnPass(Catcher); break;
// etc
}
}
This would allow me to call the function as:
MyWeapon->Catch(Catcher, Method::Pickup);
MyWeapon->Catch(Catcher, Method::Pass);
and the likes. I think this would read nicer than
MyWeapon->CatchByPickup(Catcher);
MyWeapon->CatchByPass(Catcher);
My main issue however, is that this is not extendable at all, which is what I was actually hoping to achieve with this general purpose method. If I make the method an enum, I cannot simply extend the enum and override the virtual Catch method in a derived class of Weapon. If I decide to extend the method in some derived class, I'd have to create a new enum which begins at the last value of the Method enum. I do not feel that this is a proper way to deal with the situation, but I do not know what the best practise in this case would be. Does it perhaps involve template specializations? The main problem to me, is that I cannot simply extend enums.
You could make use of std::function.
using CatchMethod = std::function<void(Character)>;
void Weapon::Catch(Character Catcher, CatchMethod Method)
{
Method(Catcher);
}
Calling the function is then pretty straightforward
// If its a regular function you can just use the pointer to the function
weapon.Catch(Player, &OnPickup);
// If its a member function you can use lambda
weapon.Catch(Player, [this](Character Catcher){OnPickup(Catcher);});
// or std::bind (slightly more verbose and less flexible)
weapon.Catch(Player, std::bind(&Weapon::OnPickup, this, std::placeholders::_1));
It's a bit non-obvious since I'm not sure if you have any other code in your Catch method that is relevant to the system, but it sounds to me like you would want to simply not use methods at all and invert the control to have different functions. Like this, for example:
void pickup(Weapon weapon, Character catcher) {
/* Do whatever your OnPickup does */
}
void pass(Weapon weapon, Character catcher) {
/* Do whatever your OnPass does */
}
And then, obviously, just call them like this:
pickup(MyWeapon, Catcher);
pass(MyWeapon, Catcher);
If there is no surrounding code or similar prerequisites that you don't show in the question, I don't think there are any back sides to this, and declaring new functions to do similar things is entirely decentralized and extensible.
If it is that you need to pass the CatchMethod through other functions, you could simply pass a function pointer instead.
As an aside, by the way, unless Weapon and Character here are typedefs to something else, it's generally a bad idea to pass these kinds of things by-value. You probably want to use references or pointers instead.

Return different types from c++ functions

Ok, so I am struggling with the following:
I have a class (A), which holds a vector<B> (a vector for Qt) of some other classes (B). The class B has a property, let's say p and also has a name.
For one case, I would like to get a listing of the B objects that are to be found in class A which have the p property set, and for another case I would like to get a list of the names of the B objects that have the property set.
And most of all, I would like to have these two functions to be called the same :)
So, something like:
class A
{
public:
QVector<B*> B_s_with_p() { ... }
QStringList B_s_with_p() { ... }
};
but I don't want to have a helper parameter to overload the methods (yes, that would be easy), and the closest I have got is a method with a different name ... which works, but it's ugly. Templates don't seem to work either.
Is there a way using todays' C++ to achieve it?
A cheat would be to use a reference to QVector<B*> or QStringList as an argument instead of a return type. That way you can overload B_s_with_p as normal. I guess you don't consider that a valid option.
Only the signature is used to overload methods. That means the return type can't be use to overload.
You have to use different methods names or manage your return value with a parameter :
class A
{
public:
void B_s_with_p(QVector<B*>&);
void B_s_with_p(QStringList&);
};
B_s_with_p() could use a template type as parameter.
Why do you think that having two different names for two different sets of functionality is ugly? That's exactly what you should be doing to delineate the different return types here.
Another alternative is to have just the function that returns an object, and then create a names_of method that you pass the list of B objects and it returns the list of names.
Check your design .. Overloaded functions are one which have similar funcionality but differnt argument types .. So check why you want to
I would like to have these two functions to be called the same
refer to :What is the use/advantage of function overloading?
The benefit of overloading is consistency in the naming of functions which perform the same task, just with different parameters.

Sharing function between classes

I have three classes which each store their own array of double values. To populate the arrays I use a fairly complex function, lets say foo(), which takes in several parameters and calculates the appropriate values for the array.
Each of my three classes uses the same function with only minor adjustments (i.e. the input parameters vary slightly). Each of the classes is actually quite similar although they each perform separate logic when retrieving the values of the array.
So I am wondering how should I 'share' the function so that all classes can use it, without having to duplicate the code?
I was thinking of creating a base class which contained the function foo() and a virtual get() method. My three classes could then inherit this base class. Alternatively, I was also thinking perhaps a global function was the way to go? maybe putting the function into a namespace?
If the classes have nothing in common besides this foo() function, it is silly to put it in a base class; make it a free function instead. C++ is not Java.
Declaring of a function in base class sounds the most appropriate solution. Not sure if you need virtual "get" though, instead just declare the array in the base class and provide access method(s) for descendants.
More complex part is "the input parameters vary slightly". If parameters differ by type only then you may write a template function. If difference is more significant than the only solution I see is splitting main function into several logic blocks and using these blocks in descendant classes to perform final result.
If your classes are quite similar, you could create a template class with three different implementations that has the function foo<T>()
Implement that function in base class. If these classes are similar as you say, they should be derived from one base class anyway! If there are several functions like foo(), it might be reasonable in some cases to combine them into another class which is utilized by/with your classes.
If the underlying data of the class is the same (Array of doubles), considering using a single class and overloading the constructor, or just use 3 different functions:
void PopulateFromString(const string&)
void PopulateFromXml(...)
void PopulateFromInteger(...)
If the data or the behavior is different in each class type, then your solution of base class is good.
You can also define a function in the same namespace as your classes as utility function, if it has nothing to do with specific class behavior (Polymorphism). Bjarne StroupStroup recommends this method by the way.
For the purpose of this answer, I am assuming the classes you have are not common in any other outwards way; they may load the same data, but they are providing different interfaces.
There are two possible situations here, and you haven't told us which one it is. It could be more like
void foo(double* arr, size_t size) {
// Some specific code (that probably just does some preparation)
// Lots of generic code
// ...
// Some more specific code (cleanup?)
}
or something similar to
void foo(double* arr, size_t size) {
// generic_code();
// ...
// specific_code();
// generic_code();
// ...
}
In the first case, the generic code may very well be easy to put into a separate function, and then making a base class doesn't make much sense: you'll probably be inheriting from it privately, and you should prefer composition over private inheritance unless you have a good reason to. You could put the new function in its own class if it benefits from it, but it's not strictly necessary. Whether you put it in a namespace or not depends on how you're organising your code.
The second case is trickier, and in that case I would advise polymorphism. However, you don't seem to need runtime polymorphism for this, and so you could just as well do it compile-time. Using the fact that this is C++, you can use CRTP:
template<typename IMPL>
class MyBase {
void foo(double* arr, size_t size) {
// generic code
// ...
double importantResult = IMPL::DoALittleWork(/* args */);
// more generic code
// ...
}
};
class Derived : MyBase<Derived> {
static double DoALittleWork(/* params */) {
// My specific stuff
return result;
}
};
This gives you the benefit of code organisation and saves you some virtual functions. On the other hand, it does make it slightly less clear what functions need to be implemented (although the error messages are not that bad).
I would only go with the second route if making a new function (possibly within a new class) would clearly be uglier. If you're parsing different formats as Andrey says, then having a parser object (that would be polymorphic) passed in would be even nicer as it would allow you to mock things with less trouble, but you haven't given enough details to say for sure.

runtime type comparison

I need to find the type of object pointed by pointer.
Code is as below.
//pWindow is pointer to either base Window object or derived Window objects like //Window_Derived.
const char* windowName = typeid(*pWindow).name();
if(strcmp(windowName, typeid(Window).name()) == 0)
{
// ...
}
else if(strcmp(windowName, typeid(Window_Derived).name()) == 0)
{
// ...
}
As i can't use switch statement for comparing string, i am forced to use if else chain.
But as the number of window types i have is high, this if else chain is becoming too lengthy.
Can we check the window type using switch or an easier method ?
EDIT: Am working in a logger module. I thought, logger should not call derived class virtual function for logging purpose. It should do on its own. So i dropped virtual function approach.
First of all use a higher level construct for strings like std::string.
Second, if you need to check the type of the window your design is wrong.
Use the Liskov substitution principle to design correctly.
It basically means that any of the derived Window objects can be replaced with it's super class.
This can only happen if both share the same interface and the derived classes don't violate the contract provided by the base class.
If you need some mechanism to apply behavior dynamically use the Visitor Pattern
Here are the things to do in order of preference:
Add a new virtual method to the base class and simply call it. Then put a virtual method of the same name in each derived class that implements the corresponding else if clause inside it. This is the preferred option as your current strategy is a widely recognized symptom of poor design, and this is the suggested remedy.
Use a ::std::map< ::std::string, void (*)(Window *pWindow)>. This will allow you to look up the function to call in a map, which is much faster and easier to add to. This will also require you to split each else if clause into its own function.
Use a ::std::map< ::std::string, int>. This will let you look up an integer for the corresponding string and then you can switch on the integer.
There are other refactoring strategies to use that more closely resemble option 1 here. For example,if you can't add a method to the Window class, you can create an interface class that has the needed method. Then you can make a function that uses dynamic_cast to figure out if the object implements the interface class and call the method in that case, and then handle the few remaining cases with your else if construct.
Create a dictionary (set/hashmap) with the strings as keys and the behaviour as value.
Using behaviour as values can be done in two ways:
Encapsulate each behaviour in it's
own class that inherit from an
interface with"DoAction" method that
execute the behavior
Use function pointers
Update:
I found this article that might be what you're looking for:
http://www.dreamincode.net/forums/topic/38412-the-command-pattern-c/
You might try putting all your typeid(...).name() values in a map, then doing a find() in the map. You could map to an int that can be used in a switch statement, or to a function pointer. Better yet, you might look again at getting a virtual function inside each of the types that does what you need.
What you ask for is possible, it's also unlikely to be a good solution to your problem.
Effectively the if/else if/else chain is ugly, the first solution that comes to mind will therefore to use a construct that will lift this, an associative container comes to mind and the default one is obviously std::unordered_map.
Thinking on the type of this container, you will realize that you need to use the typename as the key and associate it to a functor object...
However there are much more elegant constructs for this. The first of all will be of course the use of a virtual method.
class Base
{
public:
void execute() const { this->executeImpl(); }
private:
virtual void executeImpl() const { /* default impl */ }
};
class Derived: public Base
{
virtual void executeImpl() const { /* another impl */ }
};
It's the OO way of dealing with this type of requirement.
Finally, if you find yourself willing to add many different operations on your hierarchy, I will suggest the use of a well-known design pattern: Visitor. There is a variation called Acyclic Visitor which helps dealing with dependencies.

Derived Functor with any return type and any parameters

I have a class that uses functors as units of work. It accepts a reference to a functor in its Run() method. To allow this class to operate on any functor, all these functors must derive from my base functor class which looks like this:
class baseFunctor{
public:
virtual void operator()()=0;
virtual baseFunctor Clone()=0;
};
This works, however obviously it restricts these functors to having an operator method that returns void and accepts no parameters. I need to be able to accept a functor in my class that can take any type of parameters and return anything. Its apparently do-able but I can't seem to find a way to do it. I have considered using templates, multiple inheritance, but I keep getting thwarted by the fact that the class that needs to run this functor must be able to accept any type, so will accept the base class type, and so will not know the actual type of the functor.
Any suggestions of what avenue to look at would be appreciated.
How will the class that calls the functor know what parameters to provide and what to do with the return value, if any?
So, if I'm reading this right, you have a "Visitor pattern." It might be a good thing for you to look up.
Someone needs to know what type the functor is to give it arguments. Often with functors, the arguments are assigned to fields of the derived class, and operator() will operate on those fields. That is, the dumb method that calls the functor and doesn't know anything about it is given the closure (method plus arguments all in one class) by someone more knowledgeable.
If you do want generic functors that take multiple arguments in the operator(), templating will get you partway there, but you'll need one per arity.
I agree with Neil. Your main class has to know what parameters to pass and what return value to expect from these functors. Can you just type-cast your "functor" to an appropriate class that supports the function with the necessary arguments and return value?
class baseFunctor
{
};
class functor1x2: public baseFunctor
{
public:
virtual void* execute(void*, void*);
}
class MainClass
{
public:
void Execute(baseFunctor* ipFunctor)
{
functor1x2* lpFunctor1x2 = dynamic_cast<functor1x2*>(ipFunctor);
if(lpFunctor1x2)
{
lpFunctor1x2->execute(NULL, NULL);
}
}
}
I'm not sure what could be accomplished with this approach that couldn't more easily be accomplished with the Visitor pattern, as Drew noted.
If you are open to using the Boost library (www.boost.org), you might find Boot.Bind and Boost.Function of particular interest. I have used them in the past to achieve something very much along the lines of what you are discussing.
If you use Boost.Bind, you can perform currying on the functors to account for differences between the number of arguments the functor expects and the number of arguments the Run method expects (i.e., zero). The code that creates the functor would have to bind any arguments to specific values and thus create a zero-argument functor that can be passed to Run().
MV
Why'd you want to return the functor? Are you storing some state as well? Some more detail will be much appreciated since it is not very clear what exactly you want to do.
If you plan to use inheritance, do look up Covariant Return Types (and the Virtual Constructor idiom).
Now, for the meat of the problem: the problem is really not with passing in a functor but with functor application. You may want to take a look at boost::lambda and boost::parameter as well.
I think you want an ellipsis argument, like varargs for C++.
Perhaps std::tr1::function is interesting for you?