[英]Elegant way to return different value types from function in c++ / c++11
我一直在尋找棧溢出的最佳方法,以從c ++中的函數返回不同的值類型,我發現了幾種很酷的方法,尤其是這種方法,它非常接近:
C ++具有不同返回類型的相同函數參數
但是有問題。 值對象只能采用/廣播字符串,因此如果我有類似這樣的內容:
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>>"
我的問題是我可以修改Value對象以支持bool,float和int嗎?
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 }
”中返回“ value”
大括號??
std::string
沒有單獨帶int
構造函數。 因此,您不能直接使用一個直接初始化std::string
。
您可以使用std::to_string
進行編譯,但是
Value RetrieveValue(std::string key)
{
//get value
int value = get_value(key, etc);
return { std::to_string(value) };
}
要在評論中回答您的問題:
{std::to_string(value)}
集合初始化一個Value
對象,即函數的返回值。
對任何T
的隱式轉換都發生在函數調用之外。 當編譯器需要將您返回的Value
分配給某個變量時,它將尋找正確的轉換。 模板化轉換運算符提供的內容。
根據您的第二條評論。 如果只想支持基本類型,則可以在std::is_fundamental
上分配支持static_assert
的異常:
template<typename T>
operator T() const //implicitly convert into T
{
static_assert(std::is_fundamental<T>::value, "Support only fundamental types");
std::stringstream ss(_value);
T convertedValue;
ss >> convertedValue
return convertedValue;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.