Templates not initializing themselves each time
Code:
template <typename OldType, typename NewType>
any & change_type(any & operand)
{
cout << operand.type().name() << " OprType" << endl;
cout << typeid(OldType).name() << " OldType" << endl;
cout << typeid(NewType).name() << " NewType" << endl;
//any::placeholder * newcontent = new any::holder<NewType>(void_cast<NewType>(any_cast<OldType>(operand)));
//any::placeholder * newcontent = new any::holder<NewType>(void_cast<NewType>(&static_cast<any::holder<OldType> *>(operand.content)->held));
OldType olddata = static_cast<any::holder<OldType> *>(operand.content)->held;//any_cast<OldType>(operand);
NewType newdata = void_cast<NewType,OldType>(olddata);
//std::swap(operand.content,newcontent);
//delete newcontent;
operand = newdata;
//any temp = void_cast<NewType>(any_cast<OldType>(operand));
//operand = temp;
return operand;
}
There's a ton of commented out stuff... that was all sorts of other stuff I tried.
Here's my main:
Code:
int main()
{
any blah = 1;
change_type<int,char>(blah);
cout << any_cast<char>(blah) << endl; // now this will work without crashing!
cout << void_cast<char> (2) << ' ' << void_cast<int> (void_cast<char> (2)) << endl;
// system("cls");
int *data1 = (int*)"abcdef";
any blah2 = data1;
// cout << blah2.type().name() << endl;
change_type<int*,char*>(blah2);
// cout << any_cast<char*>(blah2) << endl;
return 0;
}
If I comment out the first change_type, it runs fine.
If I comment out the second one instead, it runs fine.
If you run both change_types, it crashes.
I cannot figure it out and its really bugging me.
Any ideas?
And if you comment out the parts in the function where it changes things, and the part where it uses cout and any_cast in main, you get this for output:
Code:
int OprType
int * OldType
char * NewType
☻ 2
int * OprType
int * OldType
char * NewType
Press any key to continue
Which is what it should be... except for the 2nd and 3rd line...
However, those are correct when the second call of change_type is commented out. Does anyone know why its doing this?
Code:
operand = void_cast<NewType>(any_cast<OldType>(operand));
has the same effect on it... it still isn't working. It doesn't seem to change the template argument the second time.
I know the problem is that the any_cast is taking the wrong OldType... it seems to work the first time, and then not change later.
I can give the exact problem now that I figured it out:
The first time you call it with <int,char>, it works fine. But if you call it with <char,int> it'll crash because it is still trying to use <int,char>... why?