2

I have two pointers. p1. p2.
p1 and p2 both point to different classes.
The classes have some similar method names,
and I'd like to call a template function twice to avoid repeated code.
Here is my function:

template <class T>
void Function(vector<T> & list, T* item, const string & itemName)

see that middle paramater, "item".. is that how my signature should look if I want the item changed?

..or should I pass it as
T* & item

..or should I pass it as
T** item

the compiler is letting a lot of things slide, but then when I go to bind everything it breaks.

How do I call that function using one of my pointers?
something about casting?? I've tried everything :\

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • Do you want to change the pointer itself, or just the pointed-to object? – Chris Lutz Oct 22 '11 at 05:06
  • 1
    Your code should work as it is. Could you post your full code to see if there are constness issues or something? – Stefan Monov Oct 22 '11 at 06:24
  • @Stefan: No, it won't work as-is because a copy of the original pointer will be passed to the function and any changes made to the pointer itself will not be visible to the caller. That is, assuming the OP wants to change what the pointer *points to*, and to be fair, the OP is being very vague. If he just wants to mutate the object itself then yes, it should work as is. – Ed S. Oct 22 '11 at 06:27
  • I would like to pass the "item" in and when it returns, it may be pointing to something else. The code compiles into object files, but when I try to link them into my executable I get issues. All the errors speak of undefined reference. maybe I'm just calling the template functions wrong? do I have to cast what I pass in? or would I be able to just call Function(list,item,itemName); – Trevor Hickey Oct 22 '11 at 06:34
  • does your project consist of several libraries? Did you define your method template in .h/.cpp or a single .hpp file? Looks like you're discussing 2 issues here that aren't related. – Philipp Oct 22 '11 at 08:48

1 Answers1

2

You should be able to call your code like this:

template <class T>
void Function(std::vector<T> & list, T* item, const std::string & itemName)
{
    list.push_back(T());
    if (item != NULL)
      item->x = 4;
}

struct A
{
    int x;
};
struct B
{
    double x;
};
A a;
B b;
std::vector<A> d;
std::vector<B> i;
Function(d, &a, "foo");
Function(i, &b, "bar");

Note that passing a parameter by reference and by pointer has slightly different meaning, e.g. pointers can be NULL, see Are there benefits of passing by pointer over passing by reference in C++?.

I wonder if it's desired to pass item by pointer and list by (non-const) reference.

Community
  • 1
  • 1
Philipp
  • 11,549
  • 8
  • 66
  • 126