Pass a container of smart pointer as argument in C++
I have a function like below
void functionA(unordered_map<string, classA*>* arg1);
I need to pass in
unordered_map<string, shared_ptr<classA>>
How could I pass in the container with shared_ptr to the function which takes in a contai开发者_Go百科ner of raw pointer? I am using C++0x here.
Thanks
Typewise unordered_map<string, shared_ptr<classA>>
and unordered_map<string, classA*>
are unrelated types.
So you can't directly pass one where the other is expected.
You can:
change the signature of your function, or
copy the data to an object of the expected type.
By the way, instead of a pointer argument, consider a reference argument.
Also, consider adding const
wherever possible – it generally helps making the code easier to understand, because you then have guarantee of non-modification.
Cheers & hth.,
Since you asked, here's what a template might look like for this function:
template <typename MAP_TYPE>
void functionA(const MAP_TYPE& arg1)
{
// Use arg1 here
}
You could use a pointer and/or make it non-const if you must. As long as the map passed in uses a compatible key type and some kind of pointer to the right type as a value, it should compile and run. Whether the pointer is a native pointer or a smart pointer will likely not make a difference, depending on how you used it in your function implementation.
You're going to have to either modify functionA, or build a temporary unordered_map of the type that it wants to receive.
精彩评论