Compile time Meta-programming, with string literals.
Posted
by Hassan Syed
on Stack Overflow
See other posts from Stack Overflow
or by Hassan Syed
Published on 2010-04-16T10:29:31Z
Indexed on
2010/04/16
10:33 UTC
Read the original article
Hit count: 682
c++
|compile-time-metaprogramm
|scott-myers-books
|compile-time-configuratio
|programming-technique
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.
So I came up with the following code, my hypothesis is that it will let me have a compile-time symbols with string literals use-able at runtime. I'm not missing anything I hope.
template<class Instance>
class TheBestThing {
public:
void set_name(const char * name_in) {
get_name() = std::string(name_in);
}
void set_fs_location(const char * fs_location_in) {
get_fs_location() = std::string(fs_location_in);
}
std::string & get_fs_location() {
static std::string fs_location;
return fs_location;
}
std::string & get_name() {
static std::string name;
return name;
}
};
struct tag {};
int main()
{
TheBestThing<tag> x;
x.set_name("xyz");
x.set_fs_location("/etc/lala");
ImportantObject<x> SinceSlicedBread;
}
© Stack Overflow or respective owner