Reputation: 71
I have a template in C++ like below
template <class TYPE>
bool writeRecordForSet(std::vector<TYPE*> entityPtr){
if(entityPtr.size()== 0) return true;
...
}
I want to use the same template for std::shared_ptr
; i.e. I have std::vector<std::shared_ptr>;
How can I use the same template?
Upvotes: 1
Views: 59
Reputation: 71
This one does not work
class Base {
public:
int getVal() { return 0; }
};
template <class Type>
bool writeRecordForSet(std::vector<Type> entityPtr) {
if (entityPtr.size() == 0) return true;
//...
for (auto iter = entityPtr.begin(); iter != entityPtr.end(); iter++) {
Type enPtr = *iter;
int myval = enPtr->getVal();
}
return true;
}
int main() {
std::vector<std::shared_ptr<Base>> vec_shared;
std::vector<int*> vec_intp;
std::vector<std::unique_ptr<Base>> vec_unique_ptr;
writeRecordForSet(vec_shared);
writeRecordForSet(vec_intp);
writeRecordForSet(vec_unique_ptr);
}
Upvotes: 0
Reputation: 3224
I may have misunderstood the question but can't you just remove the * from the tempaltised function? Something like:
class Base {};
template <class Type>
bool writeRecordForSet(std::vector<Type> entityPtr){
if(entityPtr.size()== 0) return true;
//...
}
int main() {
std::vector<std::shared_ptr<Base>> vec_shared;
std::vector<int*> vec_intp;
std::vector<std::unique_ptr<Base>> vec_unique_ptr;
writeRecordForSet(vec_shared);
writeRecordForSet(vec_intp);
writeRecordForSet(vec_unique_ptr);
}
This way you could use both vector<type*>
as well as vector<shared_ptr>
as arguments to the function. (Or any other pointer type like unique_ptr)
Upvotes: 2