0

我的主要课程是:

class Data{
public:
    Data(std::string name):name_(name){};
    virtual ~Data(){};

protected:
    std::string name_;
};

由于我想允许任何类型的数据,我使用模板来创建我的继承类:

template<typename Type>
class GenericData : public Data{
 public:
    GenericData(std::string name, Type t);

private:
    Type t_;
};

template<typename Type>
GenericData<Type>::GenericData(std::string name, Type t):
    Data(name),
    t_(t)
{}

第三类是 (Generic)Data 的集合:

class Input{
public:
    Input();
    ~Input();

private:
    std::vector<Data*> d_;
};

Input::Input(){
    d_.push_back(new GenericData("double",3.2);
    d_.push_back(new GenericData("int",2);
}

Input::~Input(){
    for(unsigned int i(0);i<d_.size();i++){
    delete d_[i];
    d_[i] = NULL;
    }
}

我不知道该怎么做是t_Input课堂上获取价值。我想要一个templata<typename Type> Type Input::get(unsigned int i)返回的方法t_。我想我应该在其中创建一个虚拟方法Data和另一个方法,GenericData但我无法使其工作。

4

2 回答 2

2

这很简单:

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

class Data{
public:
    Data(std::string name):name_(name){};
    virtual ~Data(){};

protected:
    std::string name_;
};

template<typename Type>
class GenericData : public Data{
 public:
    GenericData(std::string name, Type t);

    Type Get() { return t_; }
private:
    Type t_;
};

template<typename Type>
GenericData<Type>::GenericData(std::string name, Type t):
    Data(name),
    t_(t)
{}

class Input{
public:
    Input() {}
    ~Input();

    void Add(Data*v) {d_.push_back(v);}
    template<typename T>
    T Get(int i) {
        return dynamic_cast< GenericData<T> *>(d_[i])->Get();
    }
private:
    std::vector<Data*> d_;
};

Input::~Input(){
    for(unsigned int i(0);i<d_.size();i++){
    delete d_[i];
    d_[i] = NULL;
    }
}

int main() {
        Input inp;
        inp.Add(new GenericData<int>("1", 1));
        inp.Add(new GenericData<double>("2", 2.0));
        std::cout << "1: " << inp.Get<int>(0) << "; 2: " << inp.Get<double>(1) << std::endl;
        return 0;
}
于 2013-10-17T09:31:40.737 回答
1

这很成问题。首先,您必须提供一些从 Data 中获取它的方法,例如:

(inside GenericData)

public:
    T GetValue()
    {
        // Consider naming t_ more informative
        return t_;
    }

其次,您可以创建一个通用方法来获取 Input 中的数据:

(inside Input)

public:
    template <typename T>
    GenericData<T> * GetData(int index)
    {
        return dynamic_cast<GenericData<T> *>(_d[index]);
    }

或者,更简单:

(inside Input)

public:
    template <typename T>
    T GetValue(int index)
    {
        return (dynamic_cast<GenericData<T> *>(_d[index]))->GetValue();
    }
于 2013-10-17T09:35:42.373 回答