【问题标题】:Can template classes have static members in C++模板类可以在 C++ 中具有静态成员吗
【发布时间】:2011-08-15 05:38:33
【问题描述】:

C++ 中的模板类可以有静态成员吗​​?既然不存在,而且在使用前不完整,这可能吗?

【问题讨论】:

  • 你的问题不清楚。这是具有静态成员的模板类:codeproject.com/KB/cpp/value_t.aspx Afloat since 2004。
  • C++ 专家更喜欢术语“类模板”,因为类模板是模板,而不是类。这有助于回避上述“它不存在”的假设。类模板显然存在。它只是还没有任何实例化,而正是那些模板实例化可以有成员。
  • 作为对此的扩展,以及@Potatoswatter 的回答,如果我想在我的类模板中声明static T foo;,会发生什么变化?在我正在考虑的用例中,将使用的类型集相当有限,可以保证它们都是基本的 POD 类型,例如intfloatuint64_tetc.etc.etc。我可以只创建我认为我需要的所有静态成员声明,​​如果有必要添加更多,如果新类型用作模板类型,导致未定义的引用?

标签: c++ templates static-members


【解决方案1】:

是的。静态成员在template< … > class { … } 块内声明或定义。如果已声明但未定义,则必须有另一个声明提供该成员的定义。

template< typename T >
class has_static {
    // inline method definition: provides the body of the function.
    static void meh() {}

    // method declaration: definition with the body must appear later
    static void fuh();

    // definition of a data member (i.e., declaration with initializer)
    // only allowed for const integral members
    static int const guh = 3;

    // declaration of data member, definition must appear later,
    // even if there is no initializer.
    static float pud;
};

// provide definitions for items not defined in class{}
// these still go in the header file

// this function is also inline, because it is a template
template< typename T >
void has_static<T>::fuh() {}

/* The only way to templatize a (non-function) object is to make it a static
   data member of a class. This declaration takes the form of a template yet
   defines a global variable, which is a bit special. */
template< typename T >
float has_static<T>::pud = 1.5f; // initializer is optional

为模板的每个参数化创建一个单独的静态成员。不可能在模板生成的所有类之间共享一个成员。为此,您必须在模板之外定义另一个对象。部分专业化的特征类可能会对此有所帮助。

【讨论】:

  • 我不确定,您对 cme​​ts 的意思是:“可以定义 const 整数类型”和“不能定义其他类型”。这对我来说意味着静态成员必须是 const,但事实并非如此。非常量整数成员的一个用例是给定 here 的 CRTP 计数器实现。
  • @LiKao:可以在类块的大括号内定义(不仅仅是声明)一个 const 整数类型。其他类型必须在大括号内声明,然后在命名空间范围内定义。
  • @LiKao:在 cmets 上扩展了一点。
  • 我之前应该问过这个问题,但是它们是如何调用的?
  • 如果要在包含此头文件的 cpp 文件中为特定类型实例化静态成员函数,您能否扩展此答案以显示您的编写方式?
猜你喜欢
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-10-13
  • 2017-07-02
相关资源
最近更新 更多