2012-07-19 142 views
0

由於我已經使用C++模板,但現在我真的需要它們,這已經有一段時間了。將模板類作爲參數傳遞給類方法並使用模板類作爲矢量模板類型

我轉載了一個我遇到的問題,我不記得解決方案是如何實現的。

#include <iostream> 
#include <vector> 

namespace problem { 
    template <typename T> 
    class data { 
     public: 
      inline data(T var) { 
       this->var = var; 
      } 
     private: 
      T var; 
    }; 

    class storage { 
     public: 
      inline void push(problem::data<T> * data) { 
       this->VData.push_back(data); 
      } 
     private: 
      std::vector<problem::data<T> *> VData; 
    }; 
}; 

int main() { 
    problem::storage * testStorage = new problem::storage(); 
    problem::data<int> * testData = new problem::data<int>(256); 

    testStorage->push(testData); 

    delete testData; 
    delete testStorage; 
    return 0; 
} 

g ++ -Wall problem.cpp給我下面的錯誤。

problem.cpp:17:35: error: ‘T’ was not declared in this scope 
problem.cpp:17:36: error: template argument 1 is invalid 
problem.cpp:21:30: error: ‘T’ was not declared in this scope 
problem.cpp:21:31: error: template argument 1 is invalid 
problem.cpp:21:34: error: template argument 1 is invalid 
problem.cpp:21:34: error: template argument 2 is invalid 
problem.cpp: In member function ‘void problem::storage::push(int*)’: 
problem.cpp:18:17: error: request for member ‘push_back’ in ‘((problem::storage*)this)->problem::storage::VData’, which is of non-class type ‘int’ 
problem.cpp: In function ‘int main()’: 
problem.cpp:29:28: error: no matching function for call to ‘problem::storage::push(problem::data<int>*&)’ 
problem.cpp:29:28: note: candidate is: 
problem.cpp:17:16: note: void problem::storage::push(int*) 
problem.cpp:17:16: note: no known conversion for argument 1 from ‘problem::data<int>*’ to ‘int*’ 

我知道我可以使用成員模板,但我用矢量做什麼?

template <typename T> 
inline void push(problem::data<T> * data) { 
    this->VData.push_back(data); 
} 

如果我使用成員模板,那麼矢量定義將會留下這些錯誤。

problem.cpp:22:30: error: ‘T’ was not declared in this scope 
problem.cpp:22:31: error: template argument 1 is invalid 
problem.cpp:22:34: error: template argument 1 is invalid 
problem.cpp:22:34: error: template argument 2 is invalid 
problem.cpp: In member function ‘void problem::storage::push(problem::data<T>*)’: 
problem.cpp:19:17: error: request for member ‘push_back’ in ‘this->.VData’, which is of non-class type ‘int’ 
+0

如果你有一個依賴它的數據成員,爲什麼不把你的整個'storage'類作爲一個模板呢? – chris 2012-07-19 11:47:23

+0

抱歉不提,但如果在我的腦海裏這將是一個好主意,我會做到這一點。事情是我將採用超過10個不同模板作爲數據成員的實際「存儲」類。 'template ' 這在我看來並不好。 :/ – TMKCodes 2012-07-19 12:03:02

+0

@Ternek所有這些投訴都有標準的解決方案,它不是**重新解釋演員!參見'Boost :: Any'(和/或類型擦除的容器),'template