Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

HELP with template casting!

this code: http://pastebin.com/f168570c8
gives the compile error:
test_templates.cpp: In function 'int main(int, char**)':
test_templates.cpp:51: error: expected `(' before 'g'
test_templates.cpp:51: error: expected `)' before ';' token
test_templates.cpp:51: error: invalid const_cast from type 'bar<lab2::Gregorian>' to type 'bar<lab2::Julian>*'

where the Julian and Gregorian are date classes that inherit from Date
How do I "make" the variable j as if it was of <template> type Georgian?
[602 byte] By [nisse829] at [2007-11-11 11:59:33]
# 1 Re: HELP with template casting!
You cannot do that with a simple cast, most likely. I will not look at the code this way, next time insert the code into your post, I do not click on links in general for security reasons. Anyway, what you can do is make a specialization with an overloaded assignment operator. Or, if the underlying types are similar enough, you can use the base type (for example you can use clock_t and int interchangeably on most platforms). Perhaps both of your types are strings or ints under the hood?
jonnin at 2007-11-11 20:55:39 >
# 2 Re: HELP with template casting!
1.
#include "gregorian.h"
2.
#include "julian.h"
3.
#include <time.h>
4.
#include <assert.h>
5.
using namespace lab2;
6.
using namespace std;
7.

8.
template <class T> struct bar{
9.
bar<T>(){
10.
dp = new T;
11.
}
12.
bar<T>(int a){
13.
dp=new T(a);
14.
}
15.

16.
bar<T> & operator=(const bar<T> &ref) {
17.
*dp=*(ref.dp);
18.
}
19.

20.
void print(){
21.
cout << *dp<<endl;
22.
};
23.
Date * dp;
24.
};
25.

26.

27.
int main(int argc, char **argv)
28.
{
29.
time_t a = time(NULL);
30.
set_k_time(a);
31.

32.
bar<Julian> j;
33.
bar<Gregorian> g;
34.
bar<Gregorian> g2(20);
35.

36.
cout << "bar<Julian> j:";
37.
j.print();
38.
cout <<"bar<Gregorian> g:";
39.
g.print();
40.
cout <<"bar<Gregorian> g2:";
41.
g2.print();
42.

43.
cout << "** g=g2 **" <<endl;
44.
g=g2;
45.
cout <<"g:";
46.
g.print();
47.
cout <<"g2;";
48.
g2.print();
49.

50.
cout << "** j=g **"<<endl;
51.
j=const_cast< bar<Julian> *>g;
52.
cout << "b";
53.
//b.print();
54.
cout <<"f";
55.
//f.print();
56.

57.
return 0;
58.
}
nisse829 at 2007-11-11 20:56:39 >