模板类可以在C ++中具有静态成员吗 [英] Can template classes have static members in C++

查看:69
本文介绍了模板类可以在C ++中具有静态成员吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中的模板类可以具有静态成员吗​​?由于它不存在并且在使用前是不完整的,这可能吗?

Can a template class in C++ have static members? Since it doesn't exist and is imcomplete before it is used, is this possible?

推荐答案

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

Yes. The static member is declared or defined inside the template< … > class { … } block. If it is declared but not defined, then there must be another declaration which provides the definition of the member.

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

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

A separate static member is created for each parameterization of the template. It is not possible to have a single member shared across all classes generated by the template. For that, you must define another object outside the template. A partially-specialized traits class might help with that.

这篇关于模板类可以在C ++中具有静态成员吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆