Thursday, 29 January 2015

C++ Alias rather than Typedef Example

I've been reading through Scott Meyers latest book, and one item I picked up on, which had passed by my eyes before; but I'd not noted, was the use of alias instead of typedef.

I used typedefs a lot in my code, to try and simplify things, well today I've created my first piece of code which would have used a typedef, but which I've used alias "using" statements for:

void ConsolePause(const unsigned int& p_Seconds,
const bool& p_Show = false,
const std::string& p_Legend = "")
if (p_Seconds > 0)
using Time = std::chrono::high_resolution_clock;
using MS = std::chrono::milliseconds;
using FSEC = std::chrono::duration<float>;
using TimePoint = std::chrono::system_clock::time_point;
using MSCount = long long;

TimePoint l_start = Time::now();
bool l_exit = false;
TimePoint l_end = Time::now();
FSEC l_duration = l_end - l_start;
MS l_durationValue = std::chrono::duration_cast<MS>(l_duration);
MSCount l_count = static_cast<MSCount>(std::round((l_durationValue.count() / 1000)));

if (l_count >= p_Seconds)

if (p_Show )
std::setfill(' ');
std::cout << "\r" << l_count;
if (!p_Legend.empty())
std::cout << " " << p_Legend;
while (true);

The code counts down on the console for the set number of seconds.

I like this, I think it's neater than the typedef system, though when I first wrote one instead of "using NAME = TYPE;"  I actually did "using TYPE = NAME;" on sort of autopilot.

Code derived from answer here: 

No comments:

Post a Comment