Jos*_*son 10 c++ types overloading function
我需要找到一些方法来模拟C++中函数返回类型的重载.
我知道没有办法直接这样做,但我希望有一些开箱即用的方法.我们正在为用户创建一个API,并且他们将传入一个数据字符串,该字符串根据字符串信息检索值.这些值是不同的类型.从本质上讲,我们希望让他们这样做:
int = RetrieveValue(dataString1);
double = RetrieveValue(dataString2);
// Obviously, since they don't know the type, they wouldn't use int =.... It would be:
AnotherFunction(RetrieveValue(dataString1)); // param of type int
AnotherFunction(RetrieveValue(dataString2)); // param of type double
Run Code Online (Sandbox Code Playgroud)
但这在C++中并不起作用(显然).现在,我们正在设置它们以便他们调用:
int = RetrieveValueInt(dataString1);
double = RetrieveValueDouble(dataString2);
Run Code Online (Sandbox Code Playgroud)
但是,我们不希望他们需要知道他们的数据字符串的类型.
不幸的是,我们不允许使用外部库,因此不使用Boost.
有什么方法可以解决这个问题吗?
只是为了澄清,我理解C++本身不能这样做.但必须有一些方法来解决它.例如,我考虑过做RetrieveValue(dataString1,GetType(dataString1)).这并没有真正解决任何问题,因为GetType也只能有一种返回类型.但我需要这样的东西.
我知道之前已经提出过这个问题,但是从另一个角度来看.我不能使用任何明显的答案.我需要一些完全开箱即用的东西,因为它对我有用,而其他问题中的任何答案都不是这种情况.
Naw*_*waz 24
你要从这开始:
template<typename T>
T RetrieveValue(std::string key)
{
//get value and convert into T and return it
}
Run Code Online (Sandbox Code Playgroud)
要支持此功能,您需要多做一些工作,以便将值转换为类型T.转换价值的一种简单方法是:
template<typename T>
T RetrieveValue(std::string key)
{
//get value
std::string value = get_value(key, etc);
std::stringstream ss(value);
T convertedValue;
if ( ss >> convertedValue ) return convertedValue;
else throw std::runtime_error("conversion failed");
}
Run Code Online (Sandbox Code Playgroud)
请注意,您仍然必须将此函数称为:
int x = RetrieveValue<int>(key);
Run Code Online (Sandbox Code Playgroud)
您可以避免提及int两次,如果您可以这样做:
Value RetrieveValue(std::string key)
{
//get value
std::string value = get_value(key, etc);
return { value };
}
Run Code Online (Sandbox Code Playgroud)
在哪里Value实施为:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样写:
int x = RetrieveValue(key1);
double y = RetrieveValue(key2);
Run Code Online (Sandbox Code Playgroud)
哪个是你想要的,对吧?