2017-01-01 81 views
1

我正在尋找堆棧溢出最好的方式來從函數返回不同的值類型在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 }
大括號?

+0

給定的值對象* *已經支持你在暗中'運營商T列出的類型( )'。您提供的錯誤消息表明您的代碼與您展示的樣本非常不同。如果你向我們展示你正在編譯的代碼,這將會有所幫助。 – greyfade

回答

2

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) }; 
} 

要回答的問題在意見:

  1. {std::to_string(value)}aggregate initializes一個Value對象,你的函數的返回值。

  2. 隱式轉換爲任何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; 
} 
+0

謝謝,請你解釋2件事我不明白 1.爲什麼返回是通過大括號 2.如何將此隱式轉換爲T工作 謝謝 – user63898

+0

@ user63898 - 請參閱我的編輯 – StoryTeller

+0

感謝分配,說你知道有什麼更好的方法來返回函數的不同類型? – user63898

相關問題