Click here to Skip to main content
15,895,656 members
Articles / Programming Languages / C++98

Debug Print in Variadic Template Style

Rate me:
Please Sign up or sign in to vote.
4.81/5 (10 votes)
12 Apr 2016CPOL6 min read 39.3K   488   26  
Debug Print using C++11 Variadic Template
#include <string>
#include <sstream>
#include <Windows.h>

std::wstring Anchor( int i )
{
	std::wstringstream stream;
	stream << i;

	std::wstring str = L"{";
	str += stream.str() + L"}";

	return str;
}

std::wstring Replace( std::wstring fmtstr, size_t index, const std::wstring& s )
{
	size_t pos = 0;
	std::wstring anchor = Anchor( index );

	while( std::wstring::npos != pos )
	{
		pos = fmtstr.find( anchor, pos );

		if( std::wstring::npos != pos )
		{
			fmtstr.erase( pos, anchor.size() );
			fmtstr.insert( pos, s );
			pos += s.size();
		}
	}

	return fmtstr;
}

std::wstring Format( std::wstring fmt, size_t index )
{
	return fmt;
}

template<typename T, typename... Args>
std::wstring Format( std::wstring fmt, size_t index, T& t, Args&... args )
{
	std::wstringstream stream;
	stream << t;

	std::wstring result = Replace( fmt, index, stream.str() );

	++index;

	std::wstring str = Format( result, index, args... );

	return str;
}

template<typename... Args>
void DebugPrint(const wchar_t *s, Args... args)
{
#ifdef _DEBUG
	std::wstring str = Format(std::wstring(s), 0, args...);

	OutputDebugStringW(str.c_str());
#endif
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Singapore Singapore
Shao Voon is from Singapore. His interest lies primarily in computer graphics, software optimization, concurrency, security, and Agile methodologies.

In recent years, he shifted focus to software safety research. His hobby is writing a free C++ DirectX photo slideshow application which can be viewed here.

Comments and Discussions