(c++)向模板传递指针
(C++) Passing a pointer into a template
我有两个指针。p1。p2。
P1和p2都指向不同的类。
这些类有一些相似的方法名,
我想调用模板函数两次,以避免重复代码。
下面是我的函数:
template <class T>
void Function(vector<T> & list, T* item, const string & itemName)
看到中间的参数"item"..如果我想更改项目,我的签名应该是这样的吗?
. .还是将其作为
传递T *,项目
. .还是将其作为
传递T * *项目
编译器让很多东西滑动,但是当我去绑定所有东西时,它就坏了。
如何使用指针调用该函数?
选角的事??我什么都试过了:
你应该能够像这样调用你的代码:
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++中通过指针传递比通过引用传递有什么好处?
我想知道是否需要通过指针传递item
,通过(非const)引用传递list
。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错