Function templates

Facing problem in declaring template function.This is first ever program i have written for learning the concept of c++ templates. Following program is from text-book.Even though it is from text-book, i am facing errors.Try it please and suggest me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>


using namespace std;

template<class T>

void swap(T &x,T &y)
{
    T temp = x;
    x=y;
    y=temp;
}
void fun(int m,int n,float a,float b)
{
    cout<<"The value before function"<<"m:"<<m<<"n:"<<n<<"a:"<<a<<"b:"<<b<<endl;
    swap(m,n);

    swap(a,b);
    cout<<"The value after function"<<"m:"<<m<<"n:"<<n<<"a:"<<a<<"b:"<<b<<endl;

}
int main()
{
    fun(100,200,25.6,26.5);
    return 0;
}
Last edited on
I am assuming it does not know if it should use your swap function or the one C++ has defined, try renaming your function slightly.
Actually there is already std::swap, and your compiler is asking you "What the hell, you just tell me "swap" and want me to, also, use the std:: namespace. Which one do you want? std::swap or ::swap?"

So, you can rename your function, or inside 'fun' instead of writing swap, you can write ::swap.

If that's not the case, rename from template <class T> into template <typename T>
Last edited on
Okay.You were right ! There is inbuilt function swap in std. Thanks to both of you."EssGeEich" in your comment by mentioning typename you want to emphasis that i should declare it as like this template <int T> ??? or if something else then i am unfamiliar with the keyword "typename" Kindly give me some reference for it.Thank you once again.
No, in that case you should exactly substitute 'class' with 'typename'. In this context, they do the same thing, but it is better to use the keyword 'typename'.

Cplusplus Templates Tutorial Page wrote:
The only difference between both prototypes is the use of either the keyword class or the keyword typename. Its use is indistinct, since both expressions have exactly the same meaning and behave exactly the same way.

But in certain cases, going further, you will have a difference between typename and class.
Last edited on
Topic archived. No new replies allowed.