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

时间:2015-04-05 18:40:47

标签: c++ templates

我有这段代码

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;
}

我的问题是我需要使用无符号和普通整数的此函数。 是否可以使用模板执行此操作。

2 个答案:

答案 0 :(得分:3)

我想你想要这样的东西:

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;
}

答案 1 :(得分:0)

将指针的声明从int c更改为N* c,因为它可能需要另一种数据类型作为参数,此外,您不能将指针的值放在正常变量中

相关问题