0

what to use in place of variant

Refer code below: Basically , I need different return type based on input value, but it does not work that way and hence below code does not compile. ------------------------------------------------ template <class T> auto getValue(int val) { if (val < 0) return "Negative value"; return val; } ------------------------------------------------ I do have option of returning std::variant, but it is not yet supported for our visual studio version (we are on VS 2019, but still variant was not available to our version.! Upgrading VS version is not in my control yet). How to solve this scenario? Basically, need different return type and cannot use variant.

16th Sep 2024, 3:00 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Respuestas
+ 3
I think it is bad practice to have a function conditionally return multiple types. Maybe it ought to return a struct or union that contains val and error string.
16th Sep 2024, 3:27 PM
Brian
Brian - avatar
+ 3
Any? since c++17 you have to check type tho, this isn't javascript https://sololearn.com/compiler-playground/cx3iw686hRBz/?ref=app
16th Sep 2024, 4:30 PM
Sharpneli
Sharpneli - avatar
+ 2
one such technique is to return a void*. ( but getting back to the original type will be a pain )
16th Sep 2024, 10:58 PM
MO ELomari
MO ELomari - avatar
0
Structure is a bad idea for me as possible values are int , double , string or float . Error string is not important as value required from function is either int, double, string or float. Structure will occupy memory unnecessary. Union is also not my choice as I have to check each time a type. I need simple result from a function with proper return type, but it seems a limitation of c++ to provide that way
16th Sep 2024, 3:34 PM
Ketan Lalcheta
Ketan Lalcheta - avatar