我需要在單個向量中存儲多種類型的模板類。C++一個包含多種類型的模板類的std :: vector
例如,爲:
template <typename T>
class templateClass{
bool someFunction();
};
我需要將存儲所有的一個載體:
templateClass<int> t1;
templateClass<char> t2;
templateClass<std::string> t3;
etc
據我知道這是不可能的,如果是會有人說怎麼樣?
如果無法解釋如何做出如下工作?
作爲解決辦法,我嘗試使用基本非模板類,並從中繼承模板類。
class templateInterface{
virtual bool someFunction() = 0;
};
template <typename T>
class templateClass : public templateInterface{
bool someFunction();
};
我然後創建了一個矢量來存儲基地「templateInterface」級:
std::vector<templateInterface> v;
templateClass<int> t;
v.push_back(t);
這將產生以下錯誤:
error: cannot allocate an object of abstract type 'templateInterface'
note: because the following virtual functions are pure within 'templateInterface'
note: virtual bool templateInterface::someFunction()
爲了解決這個錯誤我在取得的功能templateInterface不是通過提供一個函數體來進行純虛擬,而是在編譯時調用該函數而不是使用overide而是在虛函數中使用body。
如:
class templateInterface{
virtual bool someFunction() {return true;}
};
template <typename T>
class templateClass : public templateInterface{
bool someFunction() {return false;}
};
std::vector<templateInterface> v;
templateClass<int> i;
v.push_back(i);
v[0].someFunction(); //This returns true, and does not use the code in the 'templateClass' function body
有什麼辦法來解決這個問題,這樣的重寫功能被使用,或者是有其他的解決方法來存儲多種模板類型中的一個載體?
看看這個鏈接http:// stackoverflow。com/questions/5627215/how-to-make-a-vector-of-template-structs – Elior 2013-05-13 17:25:11