C ProgrammingDiscussion
Templates

ThePornAmbitionMay 22, 2007 3:01am
Hello. I haven't been programming for very long. I am trying a template experiment but it doesn't seem to work. I can't find the problem. Anyone care to take a look? Do I need to use pointers?

#include cstdlib
#include iostream

using namespace std;

template class T
T add( T a, T b ) {

a + b;

return;
}

int main(int argc, char *argv[])
{
int x = 5, y = 10;

int add (int x, int y );

cout << x << ' ' << y << endl;

system("PAUSE");
return EXIT_SUCCESS;
}

Angle brackets had to be left out for this post...

**EDIT** I see the problem!!!! I think, lemme try it...

Ok, no that wasn't it. I called the function template(?) 'swap' but I called upon it using the name 'add'. That still hasn't fixed the problem though. I changed it in the post too.


Sponsor
kamesanMay 22, 2007 5:12pm
You might want to study and try the example described in the template section of C++ FAQ Lite at: faq-35.3

ThePornAmbitionMay 23, 2007 2:39am
Ok, I'll give it a try. Thanks!

**EDIT** Ok, I figured it out!
It's too complicated to explain all of my mistakes in my provided example but the number one mistake was writing my template function call like this: (I will use braces in place of angle brackets) name{int}( int x, int y );
The two int before the 'x' and the 'y' were unnecessary. Thanks kamesan.


Sponsor
ThlayliMay 25, 2007 11:31am
BTW, check out Tag Blaster for an easy way to post code without replacing brackets.

ThePornAmbitionMay 25, 2007 3:14pm
Testing tag blaster:

#include <cstdlib>
#include <iostream>

using namespace std;


template< typename T >
T multiply( T a, T b ) {
T c;
c = a * b;
return( c );
}


int main(int argc, char *argv[])
{
int i1 = 5, i2 = 5, a;
double d1 = 6.6, d2 = 6.6, b;
float f1 = 34.5, f2 = 34.5, c;

a = multiply( i1, i2 );
b = multiply( d1, d2 );
c = multiply( f1, f2 );

cout << a << ' ' << b << ' ' << c << endl;

system("PAUSE");
return EXIT_SUCCESS;
}

Test successful! Nice work Thlayli!


Sponsor
ThlayliMay 26, 2007 8:05am
Sweet, is that the working code as well?

ThePornAmbitionMay 26, 2007 9:06am
yup! at least for dev-cpp...


Templates

You need to Sign-up for StumbleUpon to post to this forum