c++ - 模板类可以在 C++ 中具有静态成员吗

标签 c++ templates static-members

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

最佳答案

是的。静态成员在 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

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

关于c++ - 模板类可以在 C++ 中具有静态成员吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5827903/

相关文章:

c++ - 在C++中获得非常长的 “No match for '运算符+'”错误

c++ - 有没有办法将所有赋值运算符(+=、*= 等)转发为隐式使用重写的直接赋值运算符 (=)?

c++ - 模板、函数指针和 C++0x

c++ - 静态库的静态成员

c++ - 具有静态成员的类的前向声明

c++ - OpenCL 内核参数中的 Char***?

c++ - 抛出多个异常时,catch block 的执行顺序是什么?为什么?

c++ - 如何修复 C++ 中的运行时错误,它通过了除 1 之外的所有测试用例

C++ 结构模板

c++ - ios_base 和静态成员