why the following explicit instantiation does not work?

Anyone can give me some hint why the following code generates compile error?

Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

template <typename Any>
void swapr(Any &a, Any &b);

int main()
{
	template swapr<int>(int &a, int &b);
	return 0;
}

template <typename Any>
void swapr(Any &c, Any &d)
{
}



tryit.cpp: In function `int main()':
tryit.cpp:12: error: expected primary-expression before "template"
tryit.cpp:12: error: expected `;' before "template"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

template <typename Any>
void swapr(Any &a, Any &b);

int main()
{
    int a = 0 , b = 0;
    swapr<int>(a, b);
	return 0;
}

template <typename Any>
void swapr(Any &c, Any &d)
{
}

I do not think you are so suppose to add template before swapr.
I am trying to do an explicit instantiation( trying to force the compiler to give me a int version of swapr without using it). Still not sure which part is wrong.
Thanks for the reply but that is not what I want.
Last edited on
Er... it sounds like it was exactly what you wanted?

All it takes to explicitly instantiate is to put the <int> there:

 
swapr<int>(a,b);  // <- the <int> explicitly says that 'Any'=='int' 


No need to put (and in fact you can't put) the 'template' keyword before the function call.
Last edited on
I guess ... As long as I use it once (do swapr for a and b), I have the definition for int. but i thought there is a way that i don't have to actually use the function but have the definition for int (try to learn sth from a book), sorry for the hair splitting(hope not) :>
Ah, for that you would need to do this:

template void swapr<int>(int, int); //like a prototype

See: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13
right, if I don't put the template in main that works.
thanks.
Topic archived. No new replies allowed.