I tried searching the forums but I've come up dry. Can anyone help me with this simple coding excercise. I wanted to template my datatype in my class, but it's coming up with errors.

//template <typename T> //----> i want to use this
class typeClass
{
private:
int myArg; //---->I was trying to use 'T myArg'
public:
};
template <typename T>
void something(T myArg)
{
T thisArg = myArg;
std::cout << thisArg << endl;
}
int main()
{
int i = 22;
float f = 22.3;
char * ch = "hello";
something(i);
something(f);
something(ch[1]);
string s = "world";
something(s);
typeClass myClass;
 
return 0;
}

Recommended Answers

All 5 Replies

Huh.. where did you come up with the weird syntax from...

//template <typename T> ----> wrong way of using templates
template < class T > 
class typeClass
{
private:
T myArg; //---->I was trying to use 'T myArg'
public:
};

template <class T> // correct way

void something(T myArg)
{
T thisArg = myArg;
std::cout << thisArg << endl;
}

int main()
{
int i = 22;
float f = 22.3;
char * ch = "hello";
something(i);
something(f);
something(ch[1]);
string s = "world";
something(s);
typeClass<int> myClass;
 
return 0;
}

Hope this helped, bye.

It's part of a code example from my prof. I'm still really green on this stuff. Any help would be appreciated.

It's part of a code example from my prof. I'm still really green on this stuff. Any help would be appreciated.

Looks like there is some problem with my browser of the forum coz the code i am trying to put to help you out is not showing up

Visit this link for the template help:
http://www.cplusplus.com/doc/tutorial/templates.html

and try to run the code below and see if it works.

template < class T > 
class typeClass
{
private:
T myArg; 
public:
};

template <class T> 
void something(T myArg)
{
T thisArg = myArg;
std::cout << thisArg << endl;
}

int main()
{
int i = 22;
float f = 22.3;
char * ch = "hello";
something(i);
something(f);
something(ch[1]);
string s = "world";
something(s);
typeClass<int> myClass;
 
return 0;
}

Hope this helped, bye.

Yeah, my coding sucks....and this question I was working on didn't help me learn anything. Your link, however, was AWESOME. Thanks for that!

Ah... now this is what many people who start on programming say, give up early and think they can never do it.

Keep going on and on, keep asking help, keep on practicing and you would be surprised at how good a coder you are ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.