Search code examples
c++templatesstatic-methods

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?


Solution

  • 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.