Yes, you can declare a static member variable inside a member function template. However, there are a few important things to note about how these interact.
First, each instantiation of the member function template gets its own copy of the static variable. This means that if you instantiate the member function template with different types, each instantiation will have a separate static variable.
Here's an example:
#include <iostream>
class MyClass {
public:
template <typename T>
void func() {
static int count = 0;
count++;
std::cout << "func<" << typeid(T).name()
<< ">: " << count << std::endl;
}
};
int main() {
MyClass obj;
obj.func<int>(); // prints: func<int>: 1
obj.func<int>(); // prints: func<int>: 2
obj.func<double>(); // prints: func<double>: 1
obj.func<int>(); // prints: func<int>: 3
}
func<int>: 1
func<int>: 2
func<double>: 1
func<int>: 3
In this code, MyClass::func
declares a static variable count
. However, because func
is a member function template, each instantiation of func
gets its own count
. So func<int>
has one count
, and func<double>
has a separate count
.
It's also worth noting that if you want to define the static variable outside the class (which is necessary if it's a class type or an array), you need to provide the full template declaration:
template<>
int MyClass::func<int>::count = 0;
This can get quite complex, especially if the class itself is also a template.
In general, it's often simpler and clearer to avoid static variables inside member function templates unless you specifically need a separate static variable for each instantiation. If you do need per-instantiation static data, consider making the entire class a template instead, and putting the static variable at the class level.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create and use member function templates in classes and structs, including syntax, instantiation, and advanced techniques