Skip to content

Instantly share code, notes, and snippets.

@bechu
Created May 15, 2013 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bechu/5583955 to your computer and use it in GitHub Desktop.
Save bechu/5583955 to your computer and use it in GitHub Desktop.
use variadic template to fill string with parameters
#include <string>
#include <iostream>
#include <sstream>
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(std::wstring s, Args... args)
{
std::wstring str = Format(s, 0, args...);
std::wcout<<str<<std::endl;
}
int main()
{
DebugPrint(L"{1} {0}", true, L"Jérôme");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment