-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvert.cpp
More file actions
82 lines (65 loc) · 2.45 KB
/
Copy pathConvert.cpp
File metadata and controls
82 lines (65 loc) · 2.45 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/////////////////////////////////////////////////////////////////////
// TemplatesIntro.cpp - Demonstrate Template Syntax //
// //
// Jim Fawcett, CSE687 - Object Oriented Design, Spring 2017 //
/////////////////////////////////////////////////////////////////////
#include "Convert.h"
#include <string>
#include <iostream>
#include <functional>
/////////////////////////////////////////////////////////////////////
// Widget class - shows user defined types can be template arguments
class Widget
{
public:
Widget(const std::string& str = "") : state(str) {}
std::string& value() { return state; }
private:
std::string state;
};
std::ostream& operator<<(std::ostream& out, Widget& widget)
{
out << widget.value();
return out;
}
std::istream& operator >> (std::istream& in, Widget& widget)
{
std::string temp;
while (in.good()) // extract all the words from widget's string state
{
in >> temp;
widget.value() += temp + " ";
}
return in;
}
/////////////////////////////////////////////////////////////////////
// lambdas that provide mildly useful local processing
std::function<void()> putLine = []() { std::wcout << "\n"; };
std::function<void(size_t)> putLines = [](size_t n) {
for (size_t i = 0; i < n; ++i)
putLine();
};
std::function<void(const std::string&, char)> titleCore = [](const std::string& msg, char underline='-') {
std::cout << "\n " << msg.c_str();
std::wcout << "\n " << std::string(msg.size() + 2, underline).c_str();
};
std::function<void(const std::string&)> Title = [](const std::string& msg) { titleCore(msg, '='); };
std::function<void(const std::string&)> title = [](const std::string& msg) { titleCore(msg, '-'); };
/////////////////////////////////////////////////////////////////////
// Demo code
int main()
{
Title("Demonstrating Templates");
putLine();
title("Demonstrating Conversion of numerical types");
std::cout << "\n conversion of integer: " << Convert<int>::toString(42);
std::cout << "\n conversion of double: " << Convert<double>::toString(3.1415927);
putLine();
title("Demonstrating Conversion of Widget type");
Widget widget("Joe Widget");
std::string widgetStore = Convert<Widget>::toString(widget);
std::cout << "\n conversion of Widget: " << widgetStore;
Widget newWidget = Convert<Widget>::fromString(widgetStore);
std::cout << "\n newWidget state = " << newWidget.value();
putLines(2);
}