You should turn on commentary on your blog, otherwise incorrect stuff
will not be corrected, improvements and alternatives will not be
available, and people might decide not to read just because any serious
blog has commentary.
In my experience with Wordpress (which you use for the blog) it does let
through the odd spammer's comment, but not so much that it's a problem.
Re your second posting about converting C++ `enum` values to strings,
that's a complex problem because it depends on what the `enum` is used
for. E.g. is it used as named bits of a bitset? That's common, and
requires different code for conversion to string than simple single values.
For example, your function
const char* MyEnumToString(MyEnum e)
{
using MapType = std::map<MyEnum, const char*>;
static MapType kMap =
{
{ MyEnum::V1, "V1" },
{ MyEnum::V2, "V2" },
{ MyEnum::V3, "V3" },
};
assert(kMap.size() == (int)MyEnum::SIZE);
return kMap[e];
}
can /silently/ expand the map with a new entry, and then in a subsequent
call, from somewhere else half a galactic diameter away, trigger the
`assert`.
You could avoid that simply by adding `const` and using `at` or `find`
instead of `operator[]`.
For the case of single values that can't be combined, and where all
possible values are named, your code would work but is not reusable.
Reusable `enum` stringification typically relies on the trick of
redefining a macro, like this:
--------------------------------------------------------------------------
#include <algorithm> // std::find
#include <iterator> // std::(begin, end)
#include <string> // std::string
//----------------------------------------- Reusable machinery:
#define IMPLEMENT_ENUM_NAME_FUNC( Enum ) \
static auto name( const Enum id ) \
-> std::string \
{ \
static struct{ Enum id; const char* name; } names[] = \
{ ENUM_ITEM_LIST }; \
\
using namespace std; \
const auto p_pair = find_if( \
begin( names ), end( names ), \
[=]( const auto& pair ) { return
pair.id == id; } \
); \
\
return (p_pair == end( names ) \
? #Enum "(" + to_string( id ) + ")" \
: string( p_pair->name) \
); \
}
//----------------------------------------- Usage example:
#define PHILOSOPHER_ENUM_ITEMS \
ENUM_ITEM( kant ) \
ENUM_ITEM( descartes ) \
ENUM_ITEM( socrates ) \
#undef ENUM_ITEM
#define ENUM_ITEM( name ) name,
#undef ENUM_ITEM_LIST
#define ENUM_ITEM_LIST PHILOSOPHER_ENUM_ITEMS
struct Philosophers
{
enum Enum{ PHILOSOPHER_ENUM_ITEMS n_values };
};
#undef ENUM_ITEM
#define ENUM_ITEM( name ) {Philosophers::name, #name},
IMPLEMENT_ENUM_NAME_FUNC( Philosophers::Enum )
#include <iostream>
auto main()
-> int
{
using namespace std;
for( int i = 0; i < Philosophers::n_values; ++i )
{
cout << name( Philosophers::Enum( i ) ) << endl;
}
cout << endl;
cout << name( Philosophers::Enum( 1234 ) ) << endl; // A not
named value.
}
--------------------------------------------------------------------------
Cheers!,
- Alf