Dear Boost,
In the prototype https://svn.boost.org/trac/boost/wiki/SoC2016 at
https://goo.gl/1CQAuQ I claim "Even with all of Boost's facilities
[1] and using C++ 14, this program represents the currently best
available method of implementing a static constant associative map of
keys to values" and you can find either the code at the link or
pasted below.
Can I quickly check here if that claim is true? Is there a better way
than my example program?
BTW by static constant associative map of keys to values I mean the
thing me and Tony van Eerd were speaking about here last year and the
year before, and indeed frequently at BlackBerry!
Niall
[1]: I believe Boost.Hana could implement a static constan
associative map quite easily, but I'd be fairly sure Hana will likely
be beyond most students.
--- cut ---
#include
#include
#include <map>
#include
#include <iostream>
using std::experimental::string_view;
enum class weekday { sunday, monday, tuesday, wednesday, thursday,
friday, saturday };
// initializer_list, pair and string_view are constexpr, so this list
can be constexpr
// (i.e. lives in the mind of the compiler only and has zero
representation in generated code)
#define STRING_VIEW(str) { str, sizeof(str)-1 }
constexpr std::initializer_list> string_to_weekday {
{ STRING_VIEW("sunday"), weekday::sunday },
{ STRING_VIEW("monday"), weekday::monday },
{ STRING_VIEW("tuesday"), weekday::tuesday },
{ STRING_VIEW("wednesday"), weekday::wednesday },
{ STRING_VIEW("thursday"), weekday::thursday },
{ STRING_VIEW("friday"), weekday::friday },
{ STRING_VIEW("saturday"), weekday::saturday }
};
int main(void)
{
{
// Calls malloc() at least 7 times
static const std::map to_weekday1 =
string_to_weekday;
std::cout << "'monday' maps to " <<
static_cast<int>(to_weekday1.at("monday")) << std::endl;
std::cout << "'friday' maps to " <<
static_cast<int>(to_weekday1.at("friday")) << std::endl;
// Calls free() at least 7 times
}
{
// Calls malloc() at least 8 times
static const std::unordered_map to_weekday2
= string_to_weekday;
std::cout << "'monday' maps to " <<
static_cast<int>(to_weekday2.at("monday")) << std::endl;
std::cout << "'friday' maps to " <<
static_cast<int>(to_weekday2.at("friday")) << std::endl;
// Calls free() at least 8 times
}
return 0;
}
--
ned Productions Limited Consulting
http://www.nedproductions.biz/
http://ie.linkedin.com/in/nialldouglas/