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.
4 ответов
+ 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.
+ 3
Any? since c++17
you have to check type tho, this isn't javascript
https://sololearn.com/compiler-playground/cx3iw686hRBz/?ref=app
+ 2
one such technique is to return a void*. ( but getting back to the original type will be a pain )
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