how to add a Integer and Real with Shared Pointers ?

I am trying to write a code that takes 2 numbers (actually 2 shared pointers of type Token) , first one real and second one Integer and multiply them together and return a number of type shared pointer of type Real with the result value.


Token is the base class. Class Integer and Class Real are user defined classes which derive from Token.

Token has a built in function called is <Type> (num1), to check if num1 is of that particular type ie is <Real>(num1) checks if num1 is of type Real.

Token has a built in function called convert <Type> (num1), to convert the underlying type of num1 to the new type ie convert <Real> (num1) , ie it will do dynamic cast down the hyrachy to downcast Token to Real.

Attempt1 fails , because there is no way i can convert a shared pointer of type Integer to Real at the line:

auto res = n1->get_value() * (n2)->get_value();

it fails because the n2 is a shared pointer of type Integer and the compiler does not know how to convert it to a shared pointer of Real.


Attempt 2 fails because Im getting the message the operand of a dynamic cast must be a pointer to a complete class type. It is telling me that n2 is not a complete class type ?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

attempt1:

	inline Token::pointer_type  perform(Token::pointer_type num1, Token::pointer_type num2)
	{

else if (is <Real>(num1) && is <Integer>(num2))
		{
			Real::pointer_type n1 = 0;
			Real::pointer_type n2 = 0;
			Real::value_type res = 0;
			Token::pointer_type l = make<Real>(0.0);
			n1 = convert<Real>(num1);
			n2 = convert<Integer>(num2);
			auto l2 = convert <Real>(l);
			auto res = n1->get_value() * (n2)->get_value();
			// use Integers setter to set the new number for newnum 
			l2->set_value(res);
			return l2;
		}

}


attempt2:


	inline Token::pointer_type  perform(Token::pointer_type num1, Token::pointer_type num2){

else if (is <Real>(num1) && is <Integer>(num2))
		{
			Real::pointer_type n1 = 0;
			Real::pointer_type n2 = 0;
			//Real::value_type res = 0;
			Token::pointer_type l = make<Real>(0.0);
			n1 = convert<Real>(num1);
			n2 = convert<Token>(num2);
			auto l2 = convert <Real>(l);
			auto res = n1->get_value() * dynamic_cast <Real*> (n2)->get_value();
			// use Integers setter to set the new number for newnum 
			l2->set_value(res);
			return l2;
		}

}
The question is what is the return type of get_value()? Another pointer?

If so dereference the pointer:

*(n1->get_value()) * *((n2)->get_value())

The result would be a value not a pointer. Hence you need to create a new object of the desired type like e.g.

make_shared<...>(*(n1->get_value()) * *((n2)->get_value()));

where the constructor takes the calculated value.
Registered users can post here. Sign in or register to post.