(C++) Passing a pointer into a template
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 :
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, eg 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.
上一篇: 当通过C ++中的引用传递时,* val和&val的区别如何?
下一篇: (C ++)将指针传递给模板