Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call static members of a template class?

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?

like image 720
Mihran Hovsepyan Avatar asked Dec 08 '10 17:12

Mihran Hovsepyan


People also ask

How do you call a static member of a class?

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.

Can template class have static function?

Yes. The static member is declared or defined inside the template< … > class { … } block.

How static members can be accessed?

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.

Are templates static?

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?


2 Answers

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.

like image 130
aschepler Avatar answered Nov 01 '22 06:11

aschepler


  1. There is no syntax for specifying that. There's little reason to make 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.
  2. Many compilers will probably do this for you automatically.
like image 26
Billy ONeal Avatar answered Nov 01 '22 07:11

Billy ONeal