(C ++)将指针传递到模板

问题描述:

我有两个指针。 p1。 p2。

p1和p2都指向不同的类。

这些类有一些类似的方法名称,

,我想调用一个模板函数两次以避免重复代码。

这是我的函数:

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)


$ b b

看到中间参数,项目..是我的签名应该怎么样,如果我想要项目改变?

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

..或者我应该将其作为

T *&项目

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

..或者我应该将其作为

T **项目传递

..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");

注意,通过引用和指针传递参数有稍微不同的含义。指针可以为NULL,请参见在C ++中通过引用传递指针是否有好处?

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++?.

我想知道是否需要传递 item 通过指针和列表通过(非const)引用。

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