Problem
This assignment has three parts:
1)
Write a void-typed function template named storeValue that allows a user to store any type of variable or object parameter into an ofstream. Essentially, you're creating a function that uses the insertion operator to write any type of variable to an output file stream.
In your definition, once you've written this value to the file stream, write a blank space " ". This way, any new values written to the stream will not be appended to the previously-written value.
You'll only need two (2) parameters, the output file stream and the value you want to store in it. Done correctly, the body of the function template should only take you 1-2 lines of code. Your ofstream parameter should be opened PRIOR to the function call and closed AFTER program control has returned back to the calling function. Remember, we want to limit the amount of work performed in a function to only the essentials.
(This section is worth 4 points out of 10)
----
----
2)
Define the overloaded insertion ( << ) operator for the Pixel class definition below:
class Pixel
{
public:
Pixel()
{
}
Pixel(int r, int g,
int b) : red(r), green(g), blue(b)
{
}
//GOAL: Define this
overloaded insertion operator
friend ostream& operator <<(ostream&, const
Pixel&);
private:
int red, green, blue;
};
Your insertion operator definition will allow your storeValue function to write a Pixel object to a file stream using this format:
(<value of red>, <value of green>, <value of blue>)
ex.: (200, 150, 100)
You do not need to add any member variables or member functions beyond the ones in this class definition; simply define the overloaded insertion operator. Done correctly, the body of this function should only take you 2-3 lines of code.
(This section is worth 4 points out of 10)
----
----
3)
In main, create an ofstream object with the file name "generic-values.txt".
Then, write three separate calls to storeValue using differently-typed value arguments:
(This section is worth 2 points out of 10)
Results
Once executing your compiled file, verify that your solution works properly by opening generic-values.txt. You should see the following content:
123 C++ (200, 150, 100)
Code:
#include <fstream>
#include <iostream>
using namespace std;
template<typename T>
void storeValue(ostream& out, T value)
{
out << value<<" ";
}
class Pixel
{
public:
Pixel()
{
}
Pixel(int r, int g, int b) : red(r), green(g),
blue(b)
{
}
//GOAL: Define this overloaded insertion
operator
friend ostream& operator <<(ostream&,
const Pixel&);
private:
int red, green, blue;
};
ostream& operator <<(ostream& out, const
Pixel& p)
{
out <<"("<< p.red << "," <<
p.blue << "," << p.green<<")\n";
return out;
}
int main()
{
ofstream fout;
fout.open("generic - values.txt");
storeValue(fout, 123);
storeValue(fout, "C++");
storeValue(fout, Pixel(200,150,100));
return 0;
}
OUTPUT:

Problem This assignment has three parts: 1) Write a void-typed function template named storeValue that allows...