+ 1
Why are there so much errors?
I don't know what happened. https://code.sololearn.com/cIcmNNLrTJIu/?ref=app
6 Antworten
+ 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
+ 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.
+ 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;
}
+ 2
@Ketan Lalcheta more about std::variant and std::visit :
http://eel.is/c++draft/variant
http://eel.is/c++draft/variant#visit
+ 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 ?
+ 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