954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Template class not converting

This is a stripped down version of an error I'm getting in a different program, but this is simpler. The problem comes from if I try to set something that isn't an int in MyClass

#include <iostream>

using namespace std;

template <typename T>
class MyClass
{
	private:
		T data;
	public:
		void Set(T const &);
		void Print();
};


template <typename T> void MyClass<T> ::Set(T const &d)
{
     data = d;
}


template <typename T> void MyClass<T>::Print()
{
        cout << data << endl;
}

int main()
{
     MyClass<int> c;
     
     c.Set("boo");
     c.Print();
     
     return 0;
}


Here is the compile results:

test.cpp: In function ‘int main()’:
test.cpp:31: error: invalid conversion from ‘const char*’ to ‘int’
test.cpp:31: error:   initializing argument 1 of ‘void MyClass<T>::Set(T) [with T = int]’


Also I got the skeleton of this code from somewhere where they used vectors and iterators with none of the problems of this

sirbriggs
Newbie Poster
3 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

>invalid conversion from ‘const char*’ to ‘int’
Yep, that's what should happen. You say that Set should take a parameter of type T, where T is specified by the template class. If you pass a value that doesn't match the type of the template class and isn't compatible, you'll get an error just as readily as if you did this:

int main()
{
  int foo = "boo";
}

>where they used vectors and iterators with none of the problems of this
They probably weren't doing the same thing. Why don't you post the code you're trying to emulate and we can tell you where you got it wrong.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Haven't you declared c as a MyClass in line 29, so why are you then trying to call Set(int const &d) with a const char*?

dougy83
Posting Whiz in Training
275 posts since Jun 2007
Reputation Points: 85
Solved Threads: 45
 

I see my problem in that file now, and it's mirrored in the other one I was talking about, it seems the file I assumed was correct (since I didn't write it) had that error in it.

Sorry for wasting you're time.

sirbriggs
Newbie Poster
3 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You