在c++中模板类可以有静态成员吗?
Can template classes have static members in C++
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
为模板的每个参数化创建一个单独的静态成员。不可能在模板生成的所有类之间共享单个成员。为此,必须在模板之外定义另一个对象。一个部分专门化的trait类可能会有帮助。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 使用静态成员声明类时遇到问题
- C++:是否可以使用非静态成员变量模板?
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 如何在复杂继承中访问静态成员变量
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- C++构造函数和静态成员
- 为什么传递非静态成员函数会导致编译错误?
- 非静态成员失败的线程调用函数
- 静态成员变量不会由 gettext 转换
- decltype:使用指针访问类的静态成员
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 非静态成员函数的 decltype 格式不正确吗?
- 如何在C++中定义静态成员结构