(C ++)将指针传递到模板 [英] (C++) Passing a pointer into a template

查看:114
本文介绍了(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.

这篇关于(C ++)将指针传递到模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆