Here is the simpliest (I think) boost-preprocessor library based approach (from stackoverflow) for converting enum values to string:
#include <boost/preprocessor.hpp>
#define X_ENUM_STRING_TOSTRING_CASE(r, data, elem) \
case elem : return BOOST_PP_STRINGIZE(elem);
#define ENUM_STRING(name, enumerators) \
enum name \
{ \
BOOST_PP_SEQ_ENUM(enumerators) \
}; \
\
inline const char* toString(name val) \
{ \
switch (val) \
{ \
BOOST_PP_SEQ_FOR_EACH( \
X_ENUM_STRING_TOSTRING_CASE, \
name, \
enumerators \
) \
default: \
assert(false); return "[Unknown " BOOST_PP_STRINGIZE(name) "]"; \
} \
}
// Usage sample:
ENUM_STRING(Button, (Ok)(Close)(Retry)(Yes)(No)(Abort)(Help)(Cancel))
void foo()
{
std::string btnHelpName = toString(Button::Help); // btnHelpName == "Help"
std::string btnCloseName = toString(Button::Close); // btnCloseName == "Close"
}
Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts
Monday, June 29, 2015
Tuesday, November 25, 2014
How to revert a singly linked list
struct Node{
Node* next;
int value;
};
Node* revert_iteratively(Node* node)
{
Node* new_node = nullptr;
while (node)
{
auto next = node->next;
node->next = new_node;
new_node = node;
node = next;
}
return new_node;
}
Node* revert_iteratively_simple(Node* node)
{
using std::swap;
for (Node* tmp = nullptr; swap(node, tmp), tmp; swap(node, tmp->next));
return node;
}
Node* revert_recursively(Node* node)
{
if (!node || !node->next)
return node;
auto new_node = revert_recursively(node->next);
node->next->next = node;
node->next = nullptr;
return new_node;
}
Sunday, December 29, 2013
Three ways to get UTC time in C++
1. C++ way:
#include <ctime>std::string currentDateTimeUTC( )
{
struct tm tm;
std::time_t time = std::time(nullptr);
if (gmtime_s(&tm, &time))
return ("");
char utc[_countof("1970-01-01T00:00:00")];
strftime(utc, _countof(utc), "%Y-%m-%dT%H:%M:%S", &tm);
return (utc);
}
auto result = currentDateTimeUTC( );
2. boost way:
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time;
auto result = to_iso_extended_string(second_clock::universal_time());
3. Qt way:
#include <QDateTime>
auto result = QDateTime::currentDateTimeUtc().toString(Qt::ISODate).toStdString();
Monday, July 16, 2012
IID_PPV_ARGS
Useful macro, instead this:
hr = CoCreateInstance(
__uuidof(FileOpenDialog), NULL, CLSCTX_ALL,
__uuidof(IFileDialogCustomize), reinterpret_cast<void**>(&pFileOpen));
we can write:
hr = CoCreateInstance(
__uuidof(FileOpenDialog), NULL, CLSCTX_ALL,
IID_PPV_ARGS(&pFileOpen));
hr = CoCreateInstance(
__uuidof(FileOpenDialog), NULL, CLSCTX_ALL,
__uuidof(IFileDialogCustomize), reinterpret_cast<void**>(&pFileOpen));
we can write:
hr = CoCreateInstance(
__uuidof(FileOpenDialog), NULL, CLSCTX_ALL,
IID_PPV_ARGS(&pFileOpen));
Subscribe to:
Posts (Atom)
