[英]C++ template function with pointer arguments
I have this code 我有这个代码
template <class N>
inline N swap(N a, N b) {
int c = *a;
*a = *b;
*b = c;
}
with this function I get this error: error: 'N' does not name a type Error compiling.
使用此功能,我会收到此错误:
error: 'N' does not name a type Error compiling.
This is my normal function. 这是我的正常功能。
inline void swap(int *a, int *b) {
int c = *a;
*a = *b;
*b = c;
}
My problem is that I need to use this function with unsigned and normal ints. 我的问题是我需要将此函数与unsigned和normal整数一起使用。 Is it possible to do this with templates.
是否可以使用模板来做到这一点。
I think you want something like this: 我想你想要这样的东西:
template<typename T>
inline void swap(T* a, T* b) // Use T* if you're expecting pointers
^^^^ // Notice the return type
{
T c = *a;
*a = *b;
*b = c;
}
将指针的声明从int c
更改为N* c
因为它可能会使用其他数据类型作为参数,此外您不能将指针的值放在普通变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.