我的主要课程是:
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)
{}
第三类是(通用)数据的集合:
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)
的{{1}}方法。我想我应该在t_
中创建一个虚拟方法,在Data
中创建另一个方法,但我无法使其工作。
答案 0 :(得分: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;
}
答案 1 :(得分: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();
}