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
		T data;
		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;
     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

8 Years
Discussion Span
Last Post by sirbriggs

>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.


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


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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.