Short note on C++14 decltype(auto) return type

are you familiar with decltype(auto) return type which is introduced in C++14?
It is used if you want to be able to perfectly forward a return type without knowing whether you are dealing with a reference or a value.
following example shows this.

class Test1
{
public:
    Test1() {}


    string & Process(string& val)
    {
        //Process val
        return val;
    }
};
class Test2
{
public:
    Test2() {}

    string  Process(string& val)
    {
        //Process val
        return val;
    }
};

Above two classes cane be passed to below function with one syntax using decltype(auto) even though their return type is different (one with reference and one without reference)

template <class T>
decltype(auto) Execute(T & Obj, String & arg)
{
     return Obj.Process(arg);
}


int main()
{
    Test1 test1;
    Test2 test2;
    string arg1 ="hello",arg2 ="arg2";
    Execute<Test1>(test1, arg1);
    Execute<Test2>(test2, arg2) = 10;
    return 0;
}

So decltype(auto) is very cool. But we have to be careful also while using this keyword.
for eg : int var =0;
decltype(var) and decltype((var)) is diferent; first one deduces to int and second one deduces to int&.

so if you are writing a function with return type decltype(auto) and you are returning a variable as shown below

decltype(auto) MyFun()
{
int x = 2;
----
retur (x);
}

the above program will crash because you are returning reference of the local variable; be careful

Short Note on Variadic Template

A variadic templates are template (class or function) which takes variable number of arguments.

C style Variadic functions (e.g. std::printf) were there in C++ very long back itself, but there is more  chance of run time issues due to type mismatch. C++ 11 onwards variadic templates got introduced. Since variadic template is based on templates it is less error prone.

Sample to find the addition of variable number of argument to a function can be easily written as follows.here We have used c++ 17 if constexpr to avoid multiple template definition for Add function.


#include <iostream>

template <class T, class... Args>
constexpr auto Add(const  T& head, Args ... tail) { 
    if constexpr (sizeof...(tail) > 0) {
       T result =  ((head + Add(tail...)));
       return result;
    }
    else
        return head;
}
int main()
{
    static_assert(Add(10, 30, 50, 90) == 180);
}

Small tip on C++11 Alias template

Alias templates is the feature introduced in C++ 11, it is a very useful feature . today we will discuss a small practice using it.Suppose I have to use a char array in my program ; in c++ 11 we can use std::array for this . Later we have to cross compile this program for different environment there we decided not to use std::array but use custom class. In such situations you can easily define your type for this two platforms as shown below.
#include <array>
#define PLATFORM1
template <size_t SIZE>
using CharArray =
#ifdef PLATFORM1
std::array<char,SIZE>;
#else
CustomArray<char, SIZE>;
#endif

int main()
{
CharArray<50> arr;
return 0;
}
The code looks clean and beatiful right? Even we are using different names for array data for different platform we can use using same using this alias template concept.

Different ways to get the name of the calling function in C++

1. Classic approach

There are different ways to get function names in GCC C++ compilers.The identifier __func__ is used to get exact function name.__FUNCTION__ is another name for __func__.The identifier __func__ is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration static const char __func__[] = “function-name”; appeared, where function-name is the name of the lexically-enclosing function.In GCC compilers if you want signature of function also you can use __PRETTY_FUNCTION__ .In MSVC _PRETTY_FUNCTION__ is not defined you can use __FUNCSIG__ instead.

Following example shows all this

#include <iostream>
using namespace std;
void LogInfo(const char* func, const std::string& msg)
{
    cout <<"["<<func<<"] :"<<msg;
}
#define Log(msg)   LogInfo(__PRETTY_FUNCTION__, msg)
class Calc
{
public:

    int Add(int num1, int num2)
    {
        Log("Addition");
        printf ("\n__FUNCTION__ = %s\n", __FUNCTION__);
        printf ("\n__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
        return num1+num2;
    }

    int Sub(int num1, int num2)
    {
        Log("Substraction");
        printf ("\n__FUNCTION__ = %s\n", __FUNCTION__);
        printf ("\n__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
        return num1-num2;
    }
};
int main()
{
    Calc cal;
    cal.Add(10,15);
    cal.Add(100,50);
    return 0;
}

Output of above code is shown below
Function_Name_output

2. C++ 20 approach

Using classic approach different compilers has different identifiers. C++ 20 onwards new method exists using std::source_location.
Following example shows this

#include <source_location>
void logInfo(const std::string& message,
             const std::source_location& location = std::source_location::current())
{
   cout <<"["<<location.function_name()<<"] :"<<message;
}

std::source_location has memeber function like file_name and line to get calling file name and line number respectively.

Specifying reference qualifier for a member function for a class in modern C++

I think you are familiar with const and non const member function for a class. Const member function means you cannot change the object on which this function is called (also it can call other const member function of this class).So in a class you can overload same function with const and non const qualifiers. So if a function is called using an object based on the type of object compiler maps which function to be called (const or non cont).This feature is there in C++ 98 and we all are familiar with it. Today I am going to explain you about another feature (similar to const and non const member function) which introduced in C++ 11.This feature is less publicized feature that is why I decided to explain.We can specify the reference qualifier (l value or R value) for a function.so we can have different overload for a function with lvalue and rvalue objects

Class MyClass
{
Public :
void func () &;  //l value 
void func() &&; //r value
};

MyClass obj;

Obj. func();  //calls l value
MyClass ().func(); //calls r value version of func

Internal implementation is , type of “this” will be lvalue and rvalue for corresponding calls implementation by compiler.

Mocking a function in C using “-Wl,–wrap ” compiler flag in GCC

if you are writing unit test for a function which uses a third party library or system functions we need to mock functions to simulate failure cases.
In C language if you are using gcc compiler there is compiler flag to mock a function(-Wl,-–wrap=Function_Name).
Recently I came across a c language unit test library called cmocka where it uses this feature of gcc to mock.

suppose I have to mock the function foo with syntax as shown below.

unsigned int foo (char* input);

then while compiling pass the compiler flag as below

gcc file.c “-Wl,–-wrap=foo” -o out

wrapped foo function will look as shown below

unsigned int __wrap_foo(char* input)
{
printf("'wrapped funtion");
return 1;
}

Using this flag you can mock any number of function and pass the compiler option as shown below

gcc file.c “-Wl,–-wrap=foo1,–wrap=foo2,–wrap=foo3” -o out

So if you are using the wrap flag for a function all call instances of function of foo will be redirected to __wrap_foo() call.Also if you want the real implementation you can call real function with __real_foo() with this flag on while compiling.
Sample source can be downloaded from my git repo: https://github.com/sadiquealy/GCC_Mocking

Please git clone the above Source code to understand it better with examples.Please read HowToCompile.txt to understand how to compile

Simple Console Redirector Class

have you written unit test for a function returning void? There can be function which returning void and just print to console some messages under different situations.So in unit test we can check that situation by reading console and checking the expected message.But reading a console is not possible straightforward; another way is redirecting console to a file and check the file content for message printed.Recently I wrote a simple class to redirect console to a file and can reset back to screen after the use.

here I am sharing it.

ConsoleRedirector.h


#ifndef CONSOLEREDIRECTOR_H
#define CONSOLEREDIRECTOR_H

/** Class for redirecting console to a specified file.
 */

#include 

using namespace std;

class ConsoleRedirector {
public:
    /**
     *   Construct a ConsoleRedirector  
     *   @param outFile redirecting file
     *   @param autoReset true if wants to reset console back to stdout when scope ends for the object
     */
    ConsoleRedirector(const string &outFile, bool autoReset = false);
    /**
     *  Resets ConsoleRedirector back to stdout
     */
    void Reset();
    /**
     *  Flushes the contents to redirected file
     */
    void Flush();

    /**
     *   Destructs Console Redirector ; if auto reset is true Reset will be called upon destruction
     *   
     */
    ~ConsoleRedirector();
private:
    const string m_sOutFile;
    bool m_AutoReset;
    FILE *m_pFp ;
};

#endif // CONSOLEREDIRECTOR_H

ConsoleRedirector.cpp

#include "consoleredirector.h"
#include "consoleredirectorexception.h"
ConsoleRedirector::ConsoleRedirector(const string& outFile, bool autoReset)
	: m_sOutFile(outFile), m_AutoReset(autoReset), m_pFp(nullptr) {

	m_pFp = freopen(outFile.c_str(), "w", stdout);
	if (!m_pFp) {
		Reset();
		throw ConsoleRedirectorException("Exception occured;Unable to redirect console to file", true);
	}
}

void ConsoleRedirector::Reset()
{
	if (!freopen("con", "w", stdout))
	{
		throw ConsoleRedirectorException("Exception occured;Unable to reset ConsoleRedirector", true);
	}

	if (m_pFp != nullptr)
	{
		m_pFp = nullptr;
	}
}

ConsoleRedirector::~ConsoleRedirector()
{
	if (m_AutoReset)
		Reset();
}


void ConsoleRedirector::Flush()
{
	if (m_pFp != nullptr)
	{
		if (fflush(m_pFp))
		{
			throw ConsoleRedirectorException("Unable to flush the file", true);
		}
	}
	else
	{
		throw ConsoleRedirectorException("Flush called with a bad file", false);
	}
}

Visual c++ (2019 ) Implementation can be available at my git hub repository: https://github.com/sadiquealy/ConsoleRedirector

Thread Pool class using modern c++

I think you are familiar with thread pool.
Thread pool will be useful when you have lot of tasks to be done parallelly by dedicated threads.

Advantage will be you can save thread creation overhead each time new task has to be executed and each task can be executed parallelly
I had got opportunity to create thread pool for both in Linux (using pthread) and windows(win32 thread).Now threading is there in C++ (C++ 11 onwards); here I will share a thread pool class using modern C++ .This thread pool class uses a blocking queue which I posted early:blocking queue

ThreadPool.h


#pragma once
#include "BlockingQueue.h"
class ThreadPool
{
public:
ThreadPool(int nSize = std::thread::hardware_concurrency()) :m_nSize(nSize), m_bRunning(true)
{

}

~ThreadPool()
{
ShutDown();
}

void Enque(ICommand * cmd)
{
mtxThreadJob.lock();
m_Jobs.push(cmd);
mtxThreadJob.unlock();
m_Cv.notify_one();
}

void Start()
{
for (int i = 0; i < m_nSize; i++)
{
Worker *pWorker = new Worker(*this);
m_Workers.push_back(pWorker);

}
}

void ShutDown()
{
{
std::unique_lock lock(mtxThreadStatus);
m_bRunning = false;
}
m_Cv.notify_all();
// Join all threads.
for (Worker *worker : m_Workers)
{
worker->Join();
delete worker;
}

m_Workers.clear();
}

volatile bool& Running()
{
return m_bRunning;
}

std::condition_variable& GetCondition()
{
return m_Cv;
}

private:
BlockingQueue& GetQueue()
{
return m_Jobs;
}

std::vector m_Workers;
BlockingQueue m_Jobs;
volatile bool m_bRunning;
std::mutex mtxThreadStatus;
std::mutex mtxThreadJob;
int m_nSize;
std::condition_variable m_Cv;
friend class Worker;
};

Worker.h


#pragma once
#include
#include
#include
class ThreadPool;
class Worker
{
public:
Worker(ThreadPool& pool) :m_Pool(pool), m_bBoolStatus(false), m_bRunning(true)
{
m_Thread = new std::thread(&Worker::ThreadFun, this);
}

void Join()
{
m_Thread->join();
}

private:
void ThreadFun();

bool m_bBoolStatus;
std::thread* m_Thread;
volatile bool m_bRunning;
ThreadPool& m_Pool;
};

Worker.cpp

#include "pch.h"
#include "Worker.h"
#include "Command.h"
#include "ThreadPool.h"

void Worker::ThreadFun()
{
while (m_Pool.Running())
{
ICommand * job = nullptr;

if (!m_Pool.GetQueue().empty()) {
job = m_Pool.GetQueue().front();
m_Pool.GetQueue().pop();
}

if (job)
job->Execute();
}
}

Source code can be downloaded from :download

File System Watcher in C++ for windows

Watching a directory for file change is a commonly occurring situations for programmers.
Languages like java or C# has built in classes for file watching.in Java The java.nio.file package provides a file change notification API, called the Watch Service API.C# has FileSystemWatcher class defined in System.IO.

C++ doesn’t have a ready made class available for File System watching ; recently I had written a class for it; here I am sharing it.
This CFileSystemWatcher is for Windows written in VC++ using win32 API.

class diagram is shown below

Source code is shown below

IFileWatcherListener.h

#pragma once
#include<string>
class IFileWatcherListener
{
public:
	virtual void OnFileChange(const std::wstring& path)  = 0;
	virtual void OnFileAdded(const std::wstring& path)   = 0;
	virtual void OnFileRemoved(const std::wstring& path) = 0;
	virtual void OnFileRenamed(const std::wstring& path) = 0;
};

CFileSystemWatcher.h

#ifndef CFILEWATCHER_H
#define CFILEWATCHER_H

#include <string>
#include <windows.h>
#include <Winbase.h>
#include <stdlib.h>
#include <stdio.h>
#include <thread>
#include <tchar.h>
#include "IFileWatcherListener.h"
#include <vector>
#define MAX_DIRS 25
#define MAX_FILES 255
#define MAX_BUFFER 4096

/*!
 *  CFileWatcher class.
 *  Watching a directory passed for file change and notifies if there is a change.
 *
 */
class CFileSystemWatcher
{

public:

	/*!
	 *
	 *
	 * \param logDir
	 */
	CFileSystemWatcher(const std::wstring& logDir);

	/*!
	 *
	 *
	 * \return
	 */
	const std::wstring& GetDir() { return m_sDir; }

	/*!
	 *
	 *
	 * \param listener
	 */
	void AddFileChangeListener(IFileWatcherListener* listener);

	/*!
	 * Starts the Watcher
	 *
	 */
	void Start();

	/*!
	 *
	 * Stops the Watcher
	 */
	void Stop();

	/*!
	 * Destructor for File Wacther
	 *
	 */
	~CFileSystemWatcher();
	/*!
	 *
	 *
	 * \return
	 */
	volatile bool Running() const { return m_bRunning; }
	/*!
	 * Sets the Running Status
	 *
	 * \param val
	 */
	void Running(volatile bool val) { m_bRunning = val; }

	/*!
	 * Funtion called when a file is chnaged in watcher directory
	 *
	 * \param fileNmae
	 */
	void OnFileChange(const std::wstring& fileNmae);

	/*!
	 *
	 * Funtion called when a file is added to watch directory
	 *
	 * \param sFile
	 */
	void OnFileAdded(const std::wstring& sFile);
	/*!
	 * Funtion called when a file is removed from watch directory
	 *
	 * \param sFile
	 */
	void OnFileRemoved(const std::wstring& sFile);
	/*!
	 * Funtion called when a file is renamed from watch directory
	 *
	 * \param sFile
	 */
	void OnFileRenamed(const std::wstring& sFile);

private:
	/*!
	 * Running Status
	 *
	 */
	volatile bool m_bRunning;

	/*!
	 *
	 * File Watcher Directory
	 */
	std::wstring m_sDir;

	/**
	 * List of listeners to be notified.
	 */
	std::vector<IFileWatcherListener*> m_Listeners;

	/*!
	 * File Watcher Thread
	 *
	 */
	std::unique_ptr<std::thread> m_pFileWatcherThread;
};

/*!
 * Internal Thread function executing  win32 file watcher API
 *
 */
void fileWatcherThread(CFileSystemWatcher& watcherObj);

#endif

CFileSystemWatcher.cpp

#include "pch.h"
#include <iostream>
#include <thread>
#include <future> 
#include "CFileSystemWatcher.h"


void fileWatcherThread(CFileSystemWatcher& watcherObj)
{
	HANDLE hDir = CreateFile(watcherObj.GetDir().c_str(), // pointer to the file name
		FILE_LIST_DIRECTORY,                // access (read/write) mode
		FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE,  // share mode
		NULL,                               // security descriptor
		OPEN_EXISTING,                      // how to create
		FILE_FLAG_BACKUP_SEMANTICS,         // file attributes
		NULL                                // file with attributes to copy
	);
	wchar_t filename[MAX_PATH];
	FILE_NOTIFY_INFORMATION Buffer[1024];
	DWORD BytesReturned;
	while (ReadDirectoryChangesW(
		hDir,                                  // handle to directory
		&Buffer,                                    // read results buffer
		sizeof(Buffer),                                // length of buffer
		TRUE,                                 // monitoring option
		FILE_NOTIFY_CHANGE_SECURITY |
		FILE_NOTIFY_CHANGE_CREATION |
		FILE_NOTIFY_CHANGE_LAST_ACCESS |
		FILE_NOTIFY_CHANGE_LAST_WRITE |
		FILE_NOTIFY_CHANGE_SIZE |
		FILE_NOTIFY_CHANGE_ATTRIBUTES |
		FILE_NOTIFY_CHANGE_DIR_NAME |
		FILE_NOTIFY_CHANGE_FILE_NAME,            // filter conditions
		&BytesReturned,              // bytes returned
		NULL,                          // overlapped buffer
		NULL// completion routine
	) && watcherObj.Running())
	{
		int offset = 0;
		FILE_NOTIFY_INFORMATION* pNotify;
		pNotify = (FILE_NOTIFY_INFORMATION*)((char*)Buffer + offset);
		wcscpy(filename, L"");
		
		wcsncpy(filename, pNotify->FileName, pNotify->FileNameLength / 2);
		
		filename[pNotify->FileNameLength / 2] = NULL;
			
		switch (Buffer[0].Action)
		{
		case FILE_ACTION_MODIFIED: 
			watcherObj.OnFileChange(filename);
			break;
		case FILE_ACTION_ADDED:  
			watcherObj.OnFileAdded(filename);
			break;
		case FILE_ACTION_REMOVED:
			watcherObj.OnFileRemoved(filename);
			break;		
		case FILE_ACTION_RENAMED_OLD_NAME: 
			watcherObj.OnFileRenamed(filename);
			break;
		case FILE_ACTION_RENAMED_NEW_NAME: 
			watcherObj.OnFileRenamed(filename);
			break;
		}		
	}

	CloseHandle(hDir);
}

CFileSystemWatcher::CFileSystemWatcher(const std::wstring& logDir):m_sDir(logDir), m_bRunning(false)
{

}

void CFileSystemWatcher::AddFileChangeListener(IFileWatcherListener* listener)
{
	m_Listeners.push_back(listener);
}

void CFileSystemWatcher::OnFileChange(const std::wstring& fileName)
{
	for (auto& listener : m_Listeners) {
		listener->OnFileChange(fileName);
	}
}

void CFileSystemWatcher::OnFileAdded(const std::wstring & sFile)
{
	for (auto& listener : m_Listeners) {
		listener->OnFileAdded(sFile);
	}
}

void CFileSystemWatcher::OnFileRemoved(const std::wstring & sFile)
{
	for (auto& listener : m_Listeners) {
		listener->OnFileRemoved(sFile);
	}
}

void CFileSystemWatcher::OnFileRenamed(const std::wstring & sFile)
{
	for (auto& listener : m_Listeners) {
		listener->OnFileRenamed(sFile);
	}
}

void CFileSystemWatcher::Start()
{
	m_bRunning = true;
	m_pFileWatcherThread = std::unique_ptr<std::thread>(new std::thread(fileWatcherThread, std::ref(*this)));
	m_pFileWatcherThread->detach();
}

void CFileSystemWatcher::Stop()
{
	m_bRunning = false;
}

CFileSystemWatcher::~CFileSystemWatcher()
{
}

Above class using a sample is shown below

// FileWatcherTest.cpp : Defines the entry point for the console application.
//

#include "pch.h"
#include <iostream>
#include <conio.h>
#include "IFileWatcherListener.h"
#include "CFileWatcher.h"

using namespace std;
class FileWatcherListener : public IFileWatcherListener
{
	// Inherited via IFileWatcherListener
	virtual void OnFileChange(const std::wstring & path) override
	{
		cout << "OnFileChange";
	}

	// Inherited via IFileWatcherListener
	virtual void OnFileAdded(const std::wstring & path) override
	{
		cout << "OnFileAdded";
	}

	// Inherited via IFileWatcherListener
	virtual void OnFileRemoved(const std::wstring & path) override
	{
		cout << "OnFileRemoved";
	}

	// Inherited via IFileWatcherListener
	virtual void OnFileRenamed(const std::wstring & path) override
	{
		cout << "OnFileRenamed";
	}

};

int main()
{
	
	/*!
	 * Creates watcher by passing the watch directory
	 * 
	 */
	CFileSystemWatcher watcher(L"D:\\Log");
	/*!
	 *
	 * Creates Linstener
	 */
	IFileWatcherListener* listener = new FileWatcherListener();
	
	//passes the listener to watcher
	watcher.AddFileChangeListener(listener);
	int choice;
	do
	{
		cout << "\n\nMENU";
		cout << "\n1. Start Directory Watcher";
		cout << "\n2. Stop Directory Watcher";
		cout << "\n3. Exit";
		cout << "\n\nEnter your choice 1-3 :";
		cin >> choice;

		switch (choice)
		{
		case 1:
		  {
			if (!watcher.Running())
				watcher.Start();
			else
				cout << "\nWatcher is already started ..";
		  }
			break;
		case 2:		
			watcher.Stop();
			break;		
		case 3: 
			exit(0);
			break;
		default:
			cout << "\nInvalid choice";
		}
	   } while (choice != 3);
	
	   
	   delete listener;

    return 0;
}


Source code can be downloaded from git repo: https://github.com/sadiquealy/FileWatcher