我還是模板類的新手。但是我有一個父類,然后是一個模板子類。
namespace Foo::Bar {
class BaseClass {
// No declarations
};
template<typename ChildClassType>
class ChildClass : public BaseClass {
public:
/// Public declarations
private:
// Private Members
};
}
編輯:包括有關 ChildClassType 的更多資訊所以我有幾個結構將使用這個模板類。
struct foofoo {
// Declarations
}
struct barbar {
// Declarations
}
我希望能夠擁有每種型別的多個子類的向量,所以我使用了
std::vector<std::unique_ptr<BaseClass>> allChildTypeVector;
std::unique_ptr<ChildClass<foofoo>> childPtr;
allChildTypeVectors.push_back(childPtr);
這是這里的其他幾個答案所推薦的。但我得到了。
沒有多載函式“std::vector<_Tp, _Alloc>::push_back .....”的實體與引數串列匹配
如果我這樣做,也會出現同樣的錯誤allChildTypeVectors.push_back(new ChildClass<ChildClassType>);
我知道我的型別出了點問題,但我似乎無法弄清楚。
uj5u.com熱心網友回復:
std::unique_ptrs 無法復制。如果您可以復制它們,它們將不是唯一的。因此,當您嘗試呼叫push_back. 如果您確實需要將 a std::unique_ptr<ChildClass<foofoo>>放置在向量中,則可以移動它:
#include <string>
#include <memory>
#include <vector>
class BaseClass {};
template<typename ChildClassType>
class ChildClass : public BaseClass {};
struct foofoo {};
int main() {
std::vector<std::unique_ptr<BaseClass>> allChildTypeVector;
std::unique_ptr<ChildClass<foofoo>> childPtr;
allChildTypeVector.push_back(std::move(childPtr));
}
ChildClass請注意,這與作為模板無關。沒有模板類。ChildClass是一個類模板,并且ChildClass<foofoo>是一個類。
那么為什么 allChildTypeVectors.push_back(new ChildClass); 不行?因為那將是理想的解決方案。
采用原始指標的建構式是顯式的。見這里:https ://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr 。您可以顯式呼叫建構式或使用std::make_unique:
allChildTypeVector.push_back(std::unique_ptr<ChildClass<foofoo>>(new ChildClass<foofoo>));
allChildTypeVector.push_back(std::make_unique<ChildClass<foofoo>>());
非顯式建構式會不太理想,因為原始指標會隱式轉換為unique_ptrs 而不會引起注意。有關詳細資訊,請參閱為什么 unique_ptr<T>(T*) 顯式?.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438915.html
