我正在编写一个将几个值保存为字符串并将它们保存在数组中的类。
在一个函数中,我需要提供用户请求列表中一项的值的功能,但是由于我们不知道值的类型,因此我需要询问用户如何转换它,因此我想到了模板功能。
示例代码在这里:
class myclass
{
vector<string> data;
myClass()
{
data=getData(); // data is filled, I don't know the data shape.
}
template <typename T>
T readData(int pos)
{
// here I should provide a way so if T is say int, then I convert data[pos] to int and then return back.
// I am thinking of using is_same<T, int> as follow:
if (std::is_same<T, int>::value)
{
return stio(data[pos]);
}
}
// is there any better way to do this?
}
显然,此方法需要很多if语句,并且如果T不在列表中,则在编译期间无法检测到它。
因此,我正在寻找一种更好的方法来执行此操作。
最佳答案
好吧,这里的一个关键是,如果您的return
-condition失败,则需要一个if
。但就更好的方法而言?是的,我想说 istringstream
为您提供了最大的功能和可靠性。有了它,您可以像下面这样编写函数:
template <typename T>
T readData(const size_t pos) {
T result{};
istringstream foo(data[pos]);
foo >> result;
return result;
}