0

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 container of raw pointer? I am using C++0x here.

Thanks

4
  • Are you in control of the definition of functionA? Commented Nov 25, 2010 at 3:52
  • Hi Fred, I could possibly define another functionB which takes in the unordered_map with shared_ptr. However, I still need the functionA and how could I avoid code duplication over here as both of the functions will be doing the same thing and the only difference is in the prototype? Commented Nov 25, 2010 at 4:00
  • One thought I had was making functionA a template, so you could pass whatever kind of map fits the expected interface. Commented Nov 25, 2010 at 4:12
  • Thanks Fred. Could you roughly shows how would be the function prototype like for using the template? Commented Nov 25, 2010 at 4:33

3 Answers 3

2

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.,

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

You're going to have to either modify functionA, or build a temporary unordered_map of the type that it wants to receive.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.