我正在将 .cpp 文件的扩展 SVN 关键字文字存储在“static char const *const”类成员中,并希望尽可能类似地存储 .h 描述。简而言之,我需要保证静态成员(大概在 .cpp 文件中)的单一实例化为存在于潜在共享 .h 文件中的自动生成的非整数文字。不幸的是,该语言没有尝试解析由在类定义之外进行的赋值产生的多个实例化,并明确禁止在类定义内进行非整数初始化。我最好的尝试(使用静态包装内部类)并不太脏,但我真的很想做得更好。有没有人有办法对下面的包装器进行模板化或者有一个完全优越的方法?
// Foo.h: class with .h/.cpp SVN info stored and logged statically
class Foo {
static Logger const verLog;
struct hInfoWrap;
public:
static hInfoWrap const hInfo;
static char const *const cInfo;
};
// Would like to eliminate this per-class boilerplate.
struct Foo::hInfoWrap {
hInfoWrapper() : text("$Id$") { }
char const *const text;
};
...
// Foo.cpp: static inits called here
Foo::hInfoWrap const Foo::hInfo;
char const *const Foo::cInfo = "$Id$";
Logger const Foo::verLog(Foo::cInfo, Foo::hInfo.text);
...
// Helper.h: output on construction, with no subsequent activity or stored fields
class Logger {
Logger(char const *info1, char const *info2) {
cout << info0 << endl << info1 << endl;
}
};
有没有办法解决静态链接地址问题,以便在字符串文字上模板化 hInfoWrap 类?在类定义外部分配的 extern char 指针在语言上是有效的,但失败的方式与直接成员初始化基本相同。我明白为什么该语言回避了整个解析问题,但如果提供倒置的 extern 成员限定符会非常方便,其中定义代码在类定义中对任何调用者都是可见的,但实际上只在一个特殊的点调用在别处声明。
无论如何,我离题了。对于我们现有的语言,模板或其他方式的最佳解决方案是什么?谢谢!
最佳答案
可能,有一个静态函数?
// Foo.h:
class Foo {
static Logger const verLog;
static char const*const getHInfo() { return "$Id$"; }
public:
static char const *const cInfo;
};
// Foo.cpp: static inits called here
char const *const Foo::cInfo = "$Id$";
Logger const Foo::verLog(Foo::cInfo, Foo::getHInfo());
关于c++ - 静态类成员的定义内初始化的最佳替代方案? (针对 SVN 关键字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2785183/