我正在写一些代码,可以真正做一些简单的编译时元编程。使用空结构标签作为编译时间符号是很常见的做法。我需要用一些运行时配置元素来装饰标签。静态变量似乎是唯一的出路(启用元编程),但静态变量需要全局声明。为了迈出Scott Myers的建议(来自Effective C++的第三版),想到了通过将静态变量声明为函数而不是类变量来初始化静态变量的初始化。编译时元编程,用字符串文字
于是我想出了下面的代码,我的假设是,这将让我有字符串文字编译时使用的符号,能够在运行时。我不会错过任何我希望的东西,只要我在初始化依赖模板类之前填充运行时字段,它就能正常工作? 。
#include <string>
template<class Instance>
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 & get_fs_location() {
static std::string fs_location;
return fs_location;
}
static std::string & get_name() {
static std::string name;
return name;
}
};
struct tag {};
typedef TheBestThing<tag> tbt;
int main()
{
tbt::set_name("xyz");
tbt::set_fs_location("/etc/lala");
ImportantObject<tbt> SinceSlicedBread;
}
编辑: 制造社会的维基。
@Hassan:我注意到刚才。但是,仍然可以使用更好的标签:)虽然收回。 – 2010-04-16 10:38:47
这些标签完全适用于任何寻找此特定问题的人。 – 2010-04-16 10:39:54
但问题是什么? – 2010-04-16 10:43:52