类型之间的转换

时间:2016-02-21 13:50:40

标签: c++ casting abstraction

我有一个用于序列化数据的抽象类,如下所示

template<class T>
class Serialize{
    public:
       virtual string serialize() = 0;
       virtual T deSerialize(string value) = 0;
 }

我还有一个数据模型如下

 class PersonModel: public Serialize<PersonModel> {
       ...
       public:
           ...
           string serialize() { return "The serialized form";}
           T deSerialize(string value) {return PersonModel();}
  }

现在我有一个通用的上下文类,如下所示:

 template<class T>
 class DC{
     private:
        vector<T> data;
     public:
        vector<string> read(){
            for each(auto i in data){
                Serialize<T> *getSerializedData = dynamic_cast<Serialize<T>*>(i);
            }
        }

C ++显示以上演员的以下错误:

  

错误C2682无法使用&#39; dynamic_cast&#39;转换自&#39; PersonModel&#39;至   &#39; Serialize<PersonModel> *&#39;

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

假设您将DC<T>的实例声明为DC<PersonModel>,则错误很明显:您无法将 -pointer对象转换为指向该对象的指针(或指向基类的指针。)

转而使用引用,实际上你不需要进行任何转换:

for (auto& i : data){
    // i is a reference which makes polymorphism work
    // i also "is-a" Serialize<PersonModel> object reference due to the inheritance
    i.serialize();  // Will work just fine, no casting needed
}