带有指针参数的C++模板函数

C++ template function with pointer arguments

本文关键字:函数 C++ 指针 参数      更新时间:2023-10-16

我有这个代码

template <class N>
inline N swap(N a, N b) {
    int c = *a;
    *a = *b;
    *b = c;
}

有了这个功能,我得到了这个错误:error: 'N' does not name a type Error compiling.

这是我的正常功能。

inline void swap(int *a, int *b) {
    int c = *a;
    *a = *b;
    *b = c;
}

我的问题是,我需要将这个函数与无符号整数和普通整数一起使用。可以用模板来做这件事吗。

我想你想要这样的东西:

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,因为它可能采用另一种数据类型作为参数,此外,您不能将指针的值放在普通变量中。