If I have:
template <class T>
class A
{
static void f()
{
// not using template parameter T
}
};
In this case A<int>::f()
is same as A<double>::f()
, but I don't want call A::f()
via the template parameter. Is there a syntax that allows calling of f()
but doesn't require the template parameter?
Because static member functions are not attached to a particular object, they can be called directly by using the class name and the scope resolution operator. Like static member variables, they can also be called through objects of the class type, though this is not recommended.
Yes. The static member is declared or defined inside the template< … > class { … } block.
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
A template is referred to as being "static" if no data is inserted into it when it is created or if it is not modified in any other way by Templafy. The opposite of a static template is a dynamic template. Was this article helpful?
The compiler doesn't know that A<T>::f()
doesn't use type parameter T
. So as it is, you must give the compiler a type any time you use f
.
But when I'm designing a template class and I notice some members/methods don't depend on template parameters, I'll often move those up to a non-template base class.
class A_Base {
public:
static void f();
};
template <class T> class A : public A_Base {
// ...
};
Now A_Base::f()
, A<int>::f()
, and A<double>::f()
really are all the same thing.
f
a static method anyway. Make it a free function instead. If you must make it a static method for some reason, implement it in terms of a free function and merely call it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With