Why are there so much errors? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why are there so much errors?

I don't know what happened. https://code.sololearn.com/cIcmNNLrTJIu/?ref=app

28th Jul 2020, 3:47 PM
Purple Requiem
Purple Requiem - avatar
6 Answers
+ 2
using auto as the return type with different return statements that return different types is ill-formed as it violates the single type rule (function in C++ can only have a single return type). this where std::variant or std::any needs to be used. If you have a few different types that could be returned via some run-time value then you could use either of those types as "generic type". std::variant → https://code.sololearn.com/c74ad92yWYfo/#cpp std::any → https://code.sololearn.com/cMc2ANuiwxAm/#cpp more info: std::variant ref → https://en.cppreference.com/w/cpp/utility/variant std::any ref → https://en.cppreference.com/w/cpp/utility/any
28th Jul 2020, 4:59 PM
MO ELomari
+ 2
You need to write cin >> var instead of cin << var. Also there's an issue with the auto type which is determined at compile time. The compiler simply looks if it can find a corresponding type for you data and uses it. But if you return int, char or float depending on user input at run time the compiler can't pick the correct type for you. You can however use a union for this purpose or even better dynamic types which are somehow supported by C++ as far I know. I can look this up if you're interested.
28th Jul 2020, 3:59 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 2
@Ketan Lalcheta you need to overload the input operator for std::variant: template <typename T, typename ...Ts> istream& operator>>(istream& in, variant<T,Ts...>& var) { visit([&](auto& value ){ in >> value; },var); return in; }
28th Jul 2020, 7:06 PM
MO ELomari
+ 2
@Ketan Lalcheta more about std::variant and std::visit : http://eel.is/c++draft/variant http://eel.is/c++draft/variant#visit
28th Jul 2020, 7:10 PM
MO ELomari
+ 1
Mohamed ELomari I also tried to do variant option but no success... Could you please help me understand line 42 to 46 specialy function body mentioning visit ?
28th Jul 2020, 5:13 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
auto prompt(string n, string type) { variant<int,float,string> s = 2; if (type=="int") { print(n); cin>>s; return s; }else if (type=="string") { print(n); cin>>s; return s; }else if (type=="float") { print(n); cin>>s; return s; }else{ cout<<"Error : bad input."<<endl; return 0; } } And sorry to bother you again on this Mohamed ELomari but above code also don't work when I try to return variant with auto as return type
28th Jul 2020, 5:15 PM
Ketan Lalcheta
Ketan Lalcheta - avatar