- Solution
In this lesson, we'll look at different solution reivews for the last exercise.
Solution 1: Using the if
Statement
Press + to interact
// dispatchIf.cpp#include <chrono>#include <iostream>enum class MessageSeverity{information,warning,fatal,};auto start = std::chrono::steady_clock::now();void writeElapsedTime(){auto now = std::chrono::steady_clock::now();std::chrono::duration<double> diff = now - start;std::cerr << diff.count() << " sec. elapsed: ";}void writeInformation(){ std::cerr << "information" << std::endl; }void writeWarning(){ std::cerr << "warning" << std::endl; }void writeUnexpected(){ std::cerr << "unexpected" << std::endl; }void writeMessage(MessageSeverity messServer){writeElapsedTime();if (MessageSeverity::information == messServer){writeInformation();}else if (MessageSeverity::warning == messServer){writeWarning();}else{writeUnexpected();}}int main(){std::cout << std::endl;writeMessage(MessageSeverity::information);writeMessage(MessageSeverity::warning);writeMessage(MessageSeverity::fatal);std::cout << std::endl;}
Explanation
Note:
std::cerr
of the classstd::ostream
represents the standard error stream. This is not a runtime error.
The function writeMessage
in line 25 displays the elapsed time in seconds in line 27 since the start of the program and a log message. It uses an enumeration in line 6 for the message severity. We used ...
Access this course and 1400+ top-rated courses and projects.