Friday, 15 April 2011

c++11 - C++: How to create an array with id,string and named constant? -



c++11 - C++: How to create an array with id,string and named constant? -

i utilize const lookup tables in code, consists of id , string. readability improve utilize symbol names (named constants) instead of id. example:

class lookuptable { map<int,string> m { {10,"red"}, {20,"blue"}, {30,"green"} }; enum { col_rd = 10, col_bl = 20, col_gr = 30 }; }; lookuptable tab; cout << tab.m[10]; // "red", using id cout << tab.m[col_bl] // "blue", using symbol cout << tab.m[11]; // typo! compiler not check cout << tab.m[col_xy]; // typo! compiler complain

using symbol names checked typos @ compile time.

but define symbol name, id , string element in 1 place, instead of defining values in upper part , defining named constants in lower part of class declaration, if table quite long. illustration write like:

mytable.init = { { col_rd, 10, "red" }, // define symbol names , { col_bl, 20, "blue" }, // values @ 1 place { col_gr, 30, "green" } };

is possible templates or in combination #define macros?

i 1 time saw technique used in varnish cache, uses macros - ok :)

in color_tags.hpp:

// define color tags color_tag(col_rd, 10, "red") color_tag(col_bl, 20, "blue") color_tag(col_gr, 30, "green")

usage in main.cpp:

#include <map> #include <string> #include <iostream> /// enumeration of different color codes, utilize bit of /// macro uglyness makes easy enum class color_type { #define color_tag(id,value, msg) id = value, #include "color_tags.hpp" #undef color_tag terminate_tag }; int main() { std::map<color_type, std::string> m = { #define color_tag(id, value, msg) {color_type::id, msg}, #include "color_tags.hpp" #undef color_tag {color_type::terminate_tag, "undefined"} }; std::cout << m[color_type::col_rd] << std::endl; std::cout << m[color_type::col_bl] << std::endl; std::cout << m[color_type::col_gr] << std::endl; homecoming 0; }

output:

$ g++ main.cpp -std=c++11 $ ./a.out reddish bluish greenish

c++ c++11 constants symbols lookup-tables

No comments:

Post a Comment