2015-08-26 60 views
0

泛型編程我有這樣的代碼:與多態性與通用矢量

struct All { public: All() {} ~All() {} }; 

template <typename T> 
struct any : public All 
{ 
    public: 
     any() : All() {} 
     ~any() {} 
     T value; 
}; 

int main() 
{ 
    any<int>* a = new any<int>; 
    a->value = 55; 

    any<string>* b = new any<string>; 
    b->value = "Hello World !"; 

    vector<All*> vec; 
    vec.push_back(a); 
    vec.push_back(b); 

    for (int i = 0; i < (int)vec.size(); i++) { 
     All* tmp = vec[i]; 
     cout << tmp->value << endl; // Error appears here 
    } 

    return 0; 
} 

與以下錯誤:

struct 'All' has no member named 'value'

而且我不知道如何避免這個錯誤。看來在for循環中tmp是一個All對象,並且所有對象都沒有成員命名值。 他們沒有辦法從All對象tmp中訪問子結構體(any)的成員變量以避免此問題並擁有完整的常規向量?

+2

您可以給'All'和'任何'添加一個'print'虛擬函數,然後調用它。 – immibis

回答

0

由於基本/派生類不是多態的,因此無法使用基本指針類型訪問-> value

您可以添加一個虛擬函數來打印該值。

#include <string> 
#include <iostream> 
#include <vector> 
using namespace std; 

struct All 
{ 
public: All() {} ~All() {} 
     virtual void print() = 0; 
}; 

template <typename T> 
struct any : public All 
{ 
public: 
    any() : All() {} 
    ~any() {} 
    T value; 

    virtual void print() override 
    { 
     cout << value << endl; 
    } 
}; 

int main() 
{ 
     auto a = std::make_shared<any<int>>(); 
a->value = 55; 

auto b = std::make_shared<any<string>>(); 
b->value = "Hello World !"; 

vector<std::shared_ptr<All>> vec; 
vec.push_back(a); 
vec.push_back(b); 

for (auto const& elem : vec) 
{ 
    elem->print(); 
} 
    return 0; 
} 
+0

但我不想將值打印到標準輸出。我想'print()'返回'any :: value'的值。但是我不能這樣做,因爲在'All'中聲明'any :: print()'時會產生麻煩,因爲我不知道聲明中的返回類型。幫我 ! – rangerprice

+0

然後刪除基類,並使用模板類型爲T的「any」類 – vito