【问题标题】:Getting / Setting static members of a template struct during runtime在运行时获取/设置模板结构的静态成员
【发布时间】:2012-11-20 00:13:15
【问题描述】:

我试图在运行时使用带有静态成员的模板结构存储类的信息,但是我无法获取或设置静态成员而不会出错。

为什么这段代码不起作用?

template <typename T>
struct InfoHolder
{
    static const char* name;    
};

int main()
{
    InfoHolder<int>::name = "This is an integer";
    cout << InfoHolder<int>::name << endl;

    return 0;
}

【问题讨论】:

    标签: c++ templates static


    【解决方案1】:

    如果您收到链接器错误。您必须在某处定义 name 变量。 (在类中声明它不会在任何地方分配它,因为它不是对象的一部分)

    在课后和 main 之前写:

    template <typename T>
    const char *InfoHolder<T>::name;
    

    这是静态数据成员的一个小不便。

    【讨论】:

      【解决方案2】:

      我看到它在其他地方被使用;

      由于结构中的静态成员没有分配,我可以使用函数中的静态成员,并返回一个指向变量的指针。

      template <typename T>
      struct InfoHolder
      {
          static const char** getName()
          {
              static const char* name;
              return &name;
          }
      };
      
      int main()
      {
          *InfoHolder<int>::getName() = "This is an integer";
          *InfoHolder<MyClass>::getName() = "This is an MyClass";
          *InfoHolder<OtherClass>::getName() = "This is an OtherClass";
          cout << *InfoHolder<int>::getName() << endl;
          cout << *InfoHolder<MyClass>::getName() << endl;
          cout << *InfoHolder<OtherClass>::getName() << endl;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-24
        • 1970-01-01
        • 1970-01-01
        • 2016-01-25
        • 2013-02-05
        • 1970-01-01
        相关资源
        最近更新 更多