簡體   English   中英

從另一個模板類訪問實例變量

[英]accessing instance variable from another template class

(主要是通過從另一個類模板訪問變量來粘貼以分離兩個問題)

我正在嘗試創建一個可以與數據加載器類一起使用以從文本文件加載數據的容器類系統

這是兩類數據:

class Customer
{
    //...
};

class Tour
{
    std::vector<Customer*> custPtrs;
    //...
};

這是我的兩個容器類:

template <class T>
class P_VContainer
{
    boost::ptr_vector<T> data;
    //...
};

template <class T>
class ListContainer
{
    std::list<T> data;
    //...
};

最后是我的數據加載器模板:

template<template<class> class T>
class DataLoader
{
    T<Customer> custList;
    T<Tour> tourList;

    //...
};

我在Customer和Tour中重載了>>運算符,以便可以將ifstream傳遞給它們,從該流中提取一行,標記化並將其放入對象實例變量中。

容器類按順序處理插入操作,數據加載器管理列表並創建ifstream,以便可以將其傳遞給對象。

這是我的問題:

我首先要加載我的客戶文件,然后填充該列表。

之后,我必須加載游覽,其中包含預訂他們的客戶的客戶ID,並且我想將這些客戶存儲在每個游覽對象中的指針向量中,以便可以輕松訪問客戶信息。

目前,我將customerIDs存儲為字符串列表,然后在加載所有游覽之后,將custList傳遞到一個搜索custList的函數中,並將其與字符串列表匹配

這意味着我必須維護兩個列表,一個字符串和另一個指針,並且基本上對所有數據進行雙重處理..考慮到數據集非常大,這意味着加載時間會更長。

所以我想知道是否有一種方法可以從Tour的重載>>運算符內部訪問custList實例變量,並在創建Tour對象時生成指針列表?

從技術上講,所有事情都在DataLoader類的范圍內發生,所以我認為應該有可能,但我只是不太確定如何進行操作。 我嘗試過這樣做,但到目前為止還沒有運氣。

任何幫助將不勝感激,並為冗長的解釋深表歉意,希望它是有意義的。

最終流的用法如下所示:

custStream >> customers >> toursStream >> tours;

為此,您必須將ifstream封裝為兩個流-供客戶和旅行使用,並將客戶列表保留在該流中,這是代碼,您可以將容器替換為自己喜歡的容器:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

class CustomersInFileStream {
public:
    std::vector<Customer> customers;
    std::ifstream &input;
    CustomersInFileStream(std::ifstream &fileIn)
        :input(fileIn){
    }
};

class ToursInFileStream {
public:
    std::vector<Customer> customers;
    std::ifstream &input;
    ToursInFileStream(std::ifstream &fileIn)
        :input(fileIn){
    }
};

CustomersInFileStream &operator>>(CustomersInFileStream &input, std::vector<Customer> customers) {
    // perform file parsing here using ifstream member
    input.customers = customers;
    return input;
}

ToursInFileStream &operator>>(CustomersInFileStream &customersStream,
                                  ToursInFileStream &toursStream) {
    toursStream.customers = customersStream.customers;
    return toursStream;
}

ToursInFileStream &operator>>(ToursInFileStream &input, std::vector<Tour> tours) {
    // perform file parsing here using ifstream member
    // you also do have customers list here
    return input;
}

int main()
{

    std::ifstream customersFile("~/customers.txt");
    std::ifstream toursFile("~/tours.txt");

    CustomersInFileStream custStream(customersFile);
    ToursInFileStream toursStream(toursFile);

    std::vector<Customer> customers;
    std::vector<Tour> tours;

    custStream >> customers >> toursStream >> tours;

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM