0

我必须vector<Base<T>*>用对象填充 aAB。我可以使用以下功能和重载来做到loadA这一点loadBoperator>>

我怎么能不拥有多个loadA(), loadB().. 而是拥有一个loadObject()? 那loadObject()会是什么样子?以下loadObj()不起作用,我强烈怀疑模板 OBJS 不是要走的路...

template<typename T>
class Base
{
    public:
        Base() {}
        Base(T tot_) : tot(tot_) {}

        void print() const 
        { std::cout << "Tot : " << tot << std::endl; }

    private:
        T tot;
};

template<typename T>
class A : public Base<T>
{
    public:
        A() : Base<T>(0) {}
        A(T a1, T a2) : Base<T>(a1+a2) {}
};


template<typename T>
class B : public Base<T>
{
    public:
        B() : Base<T>(1) {}
        B(T b1, T b2, T b3) : Base<T>(b1+b2+b3){}
};

template <typename T>
std::istream & operator>>(std::istream& in, A<T>& a)
{ 
    T a1, a2;
    in >> a1; 
    in >> a2;

    a = A<T>(a1,a2);

    return in;
}

template <typename T>
std::istream & operator>>(std::istream& in, B<T>& b)
{ 
    T b1, b2, b3;
    in >> b1; 
    in >> b2;
    in >> b3;

    b = B<T>(b1,b2,b3);

    return in;
}

template <typename T> // from file with 2 columns of type T
bool loadA(const std::string& s, 
                                        std::vector<A<T>>& as)
{
    A<T> a;
    std::ifstream is(s.c_str());
    if (is.good())
    {
        while (!is.eof()) 
        {
            is >> a;
            as.push_back(a);
        }
        is.close();
        return true;
    }
    return false;
}

template <typename T> // from file with 2 columns of type T
bool loadB(const std::string& s, 
                                        std::vector<B<T>>& bs)
{
    B<T> b;
    std::ifstream is(s.c_str());
    if (is.good())
    {
        while (!is.eof()) 
        {
            is >> b;
            bs.push_back(b);
        }
        is.close();
        return true;
    }
    return false;
}

template <typename T, typename OBJS>
bool loadObj(const std::string& s, OBJS o, 
                                        std::vector<Base<T>*>& objs)
{
    OBJS *pO = new OBJS;
    std::ifstream is(s.c_str());
    if (is.good())
    {
        while (!is.eof()) 
        {
            is >> o;
            objs.push_back(pO);
        }
        is.close();
        return true;
    }
    return false;
}

//// IN MAIN
// WHAT IM CURRENTLY DOING
    std::vector<A<T>> as;
    std::string filename = "test";
    loadA(filename, as);

//  for (size_t i=0; i<as.size(); ++i)
//      as[i].print();

    std::vector<Base<T>*> os;

    for (size_t i=0; i<as.size(); ++i)
        os.push_back(&as[i]);

    for (size_t i=0; i<os.size(); ++i)
        os[i]->print();

// WHAT I WOULD LIKE TO DO WITH LOADOBJ

    std::vector<Base<T>*> os2;

    loadObj(filename, A<T>(), os2);

//loadObj(filename2, B<T>(), os2)); ...

    for (size_t i=0; i<os2.size(); ++i)
        os2[i]->print();  // print 0 for all objects instead of the ones in the file "test"
4

0 回答 0