static_cast

Im trying to swap the values of an integer and a character, however Im not sure where to insert the static_cast<type> part that I need for this to happen, can I get any help?

Thank you

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
// Program to demonstrate a function template
#include <iostream>
using namespace std;

// Interchanges the values of variable1 and variable2

template<class T>
void swap_values(T& variable1, T& variable2)
{
	T temp;

	temp = variable1;
	variable1 = variable2;
	variable2 = temp;
}

int main()
{
	int integer1 = 1, integer2 = 2;
	//cout << "Original integer values are " << integer1 << " " << integer2 << endl;

	//swap_values(integer1, integer2);
	//cout << "Swapped integer values are " << integer1 << " " << integer2 << endl;


	char symbol1 = 'A', symbol2 = 'B';
	cout << "Original values are " << integer1 << " " << symbol2 << endl;

	swap_values(integer1, symbol2);
	cout << "Swapped values are " << integer1 << " " << symbol2 << endl;

	return 0;
}
That's tricky, and you should not be casting there.

A static_cast can create a new bit-pattern for your value, so it's not a condidate to be passed by reference.

Why not create a swap that takes two different types and let the language do the conversion, as in:
1
2
template <typename T, typename U>
void swap_value(T& t, U& u)

Last edited on
Thank you for the feedback, but I really need to be able to do this swap using static_cast, currently Im having a lot of trouble with the T&, but I cant remove the & because it stops the program from working
I would suggest you declare the symbol1 and symbol2 as int.
Unfortunately, that sort of defeats the purpose, due to the fact that I now recieve a 65 as the value rather than 'A' if its symbol one, so yes it swaps, but no, it is not what is needed sadly, thanks for the input though, I appreciate it
How about the following:

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
// Program to demonstrate a function template
#include <iostream>
using namespace std;

// Interchanges the values of variable1 and variable2

template<class T>
void swap_values(T& variable1, T& variable2)
{
	T temp;

	temp = variable1;
	variable1 = variable2;
	variable2 = temp;
}

int main()
{
	int integer1 = 1, integer2 = 2;
	//cout << "Original integer values are " << integer1 << " " << integer2 << endl;

	//swap_values(integer1, integer2);
	//cout << "Swapped integer values are " << integer1 << " " << integer2 << endl;


	int symbol1 = 'A', symbol2 = 'B';
	cout << "Original values are " << integer1 << " " << char(symbol2) << endl;

	swap_values(integer1, symbol2 );
	cout << "Swapped values are " << char(integer1) << " " << symbol2 << endl;

	return 0;
}
Topic archived. No new replies allowed.