模板和字符串转换

Templates and string conversion

我正在创建一个通用 class,计划从文件 read/write。

因此我不确定将实例化什么类型。 如何在读取阶段将字符串转换为某种未知类型?

IE

template<class T>
void fromString(std::string from, T to) {
    to = from; 
}

无论如何要做到这一点而不专门研究大量 classes?

惯用的方法是使用这样的东西:

template<typename T>
void fromString(std::string from, T& to) {
    std::istringstream iss(from);
    iss >> to; 
}

大部分用于解析字符串输入格式的可用标准专业化将包含在已经可用的 std::istream& operator>>(std::istream&, T&); 专业化中。


Anyway to do this without specializing for a numerous amount of classes?

不,您仍然需要针对各种 类 进行专业化,例如

class Foo {
private:
    int x;
    double y;
public:
   std::istream& getFromStream(std::istream& input) {
       input >> x;
       input >> y;
       return input;
   }
};

std:istream& operator>>(std::istream& is, Foo& subject) {
    return subject.getFromStream(is);
}