Debug Assertion Dialog For C++
 
Improved debug assertion box for C++. A better one than the _ASSERTE in MFC.                                                                                                  Home

Following is the revised version of the Debug Assert class. Thanks to Sanjeev for sharing his comments and ideas.

#pragma once

#include <atlbase.h>
#include <string>
#include <sstream>
#include <iostream>

typedef std::basic_string<TCHAR> TString;
typedef std::basic_ostringstream<TCHAR> TOStringStream;

class Debug
{
public: static void Assert(bool condition)
{
#ifdef _DEBUG
DisplayAssertBox(condition, _T(""));
#endif
}

public: static void Assert(bool condition,
const TString& assertionText,
const TString& fileName = _T(""),
int lineNumber = -1)
{
#ifdef _DEBUG
TOStringStream ast;
ast << assertionText.c_str() << std::endl;

if (!fileName.empty())
{
ast << _T("File: ") << fileName.c_str() << std::endl;
}

if (lineNumber > 0)
{
ast << _T("Line: ") << lineNumber ;
}

DisplayAssertBox(condition, ast.str());
#endif
}

private: static void DisplayAssertBox(bool condition,
const TString& assertionText)
{
#ifdef _DEBUG
if (!condition && !assertionText.empty())
{
::MessageBox(NULL,
assertionText.c_str(),
_T("Debug Assertion Dialog"),
MB_OK | MB_ICONEXCLAMATION);
}
#endif
}
};

Previous Version:

#pragma once

#include <atlbase.h>
#include <string>
#include <sstream>
#include <iostream>

class Debug
{
public: static void Assert(bool condition)
{
#ifdef _DEBUG
DisplayAssertBox(condition, "");
#endif
}

public: static void Assert(bool condition,
const std::string& assertionText,
const std::string& fileName = "",
int lineNumber = -1)
{
#ifdef _DEBUG
std::ostringstream ast;
ast << assertionText.c_str() << std::endl;

if (!fileName.empty())
{
ast << "File: " << fileName.c_str() << std::endl;
}

if (lineNumber > 0)
{
ast << "Line: " << lineNumber ;
}

DisplayAssertBox(condition, ast.str());
#endif
}

public: static void Assert(bool condition,
const std::wstring& assertionText,
const std::wstring& fileName = L"",
int lineNumber = -1)
{
#ifdef _DEBUG
std::wostringstream ast;
ast << assertionText.c_str() << std::endl;

if (!fileName.empty())
{
ast << "File: " << fileName.c_str() << std::endl;
}

if (lineNumber > 0)
{
ast << "Line: " << lineNumber ;
}

DisplayAssertBox(condition, ast.str());
#endif
}

private: static void DisplayAssertBox(bool condition,
const std::string& assertionText)
{
#ifdef _DEBUG
if (!condition && !assertionText.empty())
{
USES_CONVERSION;

::MessageBox(NULL,
A2W(assertionText.c_str()),
L"Debug Assertion Dialog",
MB_OK | MB_ICONEXCLAMATION);
}
#endif
}

private: static void DisplayAssertBox(bool condition,
const std::wstring& assertionText)
{
#ifdef _DEBUG
if (!condition && !assertionText.empty())
{
::MessageBox(NULL,
assertionText.c_str(),
L"Debug Assertion Dialog",
MB_OK | MB_ICONEXCLAMATION);
}
#endif
}
};