2017-01-01 283 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

相关问题