(C++) Passing a pointer into a template

你离开我真会死。 提交于 2019-12-12 17:03:58

问题


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 :\


回答1:


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.



来源:https://stackoverflow.com/questions/7857518/c-passing-a-pointer-into-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!