【发布时间】:2023-03-12 02:05:01
【问题描述】:
我在堆栈溢出中寻找从 c++ 中的函数返回不同值类型的最佳方法
我发现了一些很酷的方法,尤其是这种方法尽可能接近:
C++ same function parameters with different return type
但是有问题。 值对象只能接受/转换字符串,所以如果我有这样的东西:
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 }
大括号??
【问题讨论】:
-
给定的值对象已经支持您使用隐式
operator T()列出的类型。您给出的错误消息表明您的代码与您显示的示例非常不同。如果您向我们展示您实际上尝试编译的代码,将会有所帮助。
标签: c++