I am working on a problem that requires me to return different return-types based on my function parameter values that I provide.
I want to do something like this --
In the code below, doSomething()
is an already existing function (used by a lot of clients) which takes mode
as a function parameter, and returns std::list<ReturnType>
already.
Based on the mode value, I had to create another sub-functionality which returns a shared_future<std::list<ReturnType>>
.
How can I change this code so that it can return one of the two return types based on the mode value?
Note: ReturnType
is a template typename
which we are using for the entire class.
Code:
std::shared_future<std::list<ReturnType> > futureValue() {
return functionReturningSharedFuture();
}
std::list<ReturnType> listValue() {
return functionReturningList();
}
std::list<ReturnType> doSomething(int mode) {
if(mode == 1){
// new functionality that I added
return futureValue(); // This (obviously) errors out as of now
}
else{
// already there previously
return listValue();
}
}
int main() {
doSomething(1);
return 0;
}
How can I change this code so that it can return one of the two return types based on the mode value?
Constraints and Issues:
- This issue could've been easily solved by function overloading if we provide an extra function parameter (like a
true
value), but that extra argument is not useful, since we are already usingmode
. Also, it isn't considered a good design to add variables which have almost no use. - One of the major constraints is that there are clients who are already using this
doSomething()
expect astd::list<ReturnType>
, and so I cannot returnboost::any
orstd::variant
or anything similar. - I tried using
std::enable_if
, but it wasn't working out since we are getting the mode value at runtime. - We can't use template metaprogramming since that would change the way our function is being called on the client-side. Something that we can't afford to do.
Thank you.
Aucun commentaire:
Enregistrer un commentaire