Note that there are some explanatory texts on larger screens.

plurals
  1. POCompile time Meta-programming, with string literals
    primarykey
    data
    text
    <p>I'm writing some code which could really do with some simple compile time metaprogramming. It is common practise to use empty-struct tags as compile time symbols. I need to decorate the tags with some run-time config elements. static variables seem the only way to go (to enable meta-programming), however static variables require global declarations. to side step this Scott Myers suggestion (from the third edition of Effective C++), about sequencing the initialization of static variables by declaring them inside a function instead of as class variables, came to mind. </p> <p>So I came up with the following code, my hypothesis is that it will let me have a compile-time symbol with string literals use-able at runtime. I'm not missing anything I hope, and that this will work correctly, as long as I populate the runtime fields before I Initialize the depending templates classes ? .</p> <pre><code>#include &lt;string&gt; template&lt;class Instance&gt; class TheBestThing { public: static void set_name(const char * name_in) { get_name() = std::string(name_in); } static void set_fs_location(const char * fs_location_in) { get_fs_location() = std::string(fs_location_in); } static std::string &amp; get_fs_location() { static std::string fs_location; return fs_location; } static std::string &amp; get_name() { static std::string name; return name; } }; struct tag {}; typedef TheBestThing&lt;tag&gt; tbt; int main() { tbt::set_name("xyz"); tbt::set_fs_location("/etc/lala"); ImportantObject&lt;tbt&gt; SinceSlicedBread; } </code></pre> <p><strong>edit:</strong> Made community wiki.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload