我正在尋找堆棧溢出最好的方式來從函數返回不同的值類型在c + +中 我發現很酷的方式,尤其是這種方法它儘可能地接近它:
C++ same function parameters with different return type從C++/C++函數返回不同值類型的優雅方法11
但有問題。 值對象可以採取/只投了弦所以,如果我有這樣的事情:
Value RetrieveValue(std::string key)
{
//get value
int value = get_value(key, etc);
return { value };
}
即時得到:
error C2440: 'return': cannot convert from 'initializer list' to 'ReturnValue'
no suitable constructor exists to convert from "int" to "std::basic_string<char, std::char_traits<char>, std::allocator<char>>"
我的問題是,我可以修改值對象還支持布爾和浮動,詮釋?
struct Value
{
std::string _value;
template<typename T>
operator T() const //implicitly convert into T
{
std::stringstream ss(_value);
T convertedValue;
if (ss >> convertedValue) return convertedValue;
else throw std::runtime_error("conversion failed");
}
}
也是爲什麼「價值」在返回:{ value }
大括號?
給定的值對象* *已經支持你在暗中'運營商T列出的類型( )'。您提供的錯誤消息表明您的代碼與您展示的樣本非常不同。如果你向我們展示你正在編譯的代碼,這將會有所幫助。 – greyfade