Reputation: 35408
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?
Upvotes: 3
Views: 165
Reputation: 96241
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.
Upvotes: 0
Reputation: 4411
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.
Upvotes: 3
Reputation: 3075
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.
Upvotes: -1
Reputation: 412
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.
Upvotes: 4