2

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.

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. Is it possible to do this with templates.

4
  • Why not use std::swap? Commented Apr 5, 2015 at 18:42
  • Because I'm using arduino and I would like to know how it works. Commented Apr 5, 2015 at 18:43
  • And what if the template type T is not an integer? Or the arguments not pointers? Commented Apr 5, 2015 at 18:46
  • How do hou call this function? Commented Apr 5, 2015 at 18:47

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

The int looks out of place.
@molbdnilo Yes, I copied it from their implementation... I'll fix it
It was fault by Arduino IDE, I have to declare template<typename T> inline void swap(T *a, T *b); before the function. But thanks.
0

Change declaration of the pointer from int c to N* c because it may take another data type as parameter , in addition to that you can't put a value of a pointer in a normal variable .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.