【问题标题】:best alternative to in-definition initialization of static class members? (for SVN keywords)静态类成员定义初始化的最佳替代方案? (对于 SVN 关键字)
【发布时间】:2010-05-06 23:24:07
【问题描述】:

我将 .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 类?在类定义之外分配的外部 char 指针在语言上是有效的,但以与直接成员初始化相同的方式失败。我明白为什么该语言会回避整个解决问题,但是如果提供了一个反向的 extern 成员限定符会非常方便,其中定义代码在类定义中对任何调用者都是可见的,但实际上只在单个特殊点处被调用在别处声明。

无论如何,我离题了。对于我们所拥有的语言、模板或其他语言,最好的解决方案是什么?谢谢!

【问题讨论】:

    标签: c++ header initialization static-members


    【解决方案1】:

    可能是静态函数?

    // 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());
    

    【讨论】:

    • 我完全忘记了类内定义的静态方法定义是合法的。这就是我最终会使用的。谢谢!
    【解决方案2】:

    也许你可以用宏做点什么。

    // Foo.h
    #define FOO_HINFO "$Id$"
    

    ...

    // Foo.cpp
    char const     *const Foo::hInfo = FOO_HINFO;
    

    我通常避免使用宏,但在这种情况下,它可能是最干净的解决方案。

    【讨论】:

    • 因为我试图找到我的同行也想使用的解决方案,如果不是 Alsk,我可能会选择这种简单的方法而不是任何“更纯粹”的包装方法让我意识到我更大的疏忽。非常感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多