How to 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() same as A<double>::f() , but I do not want to call A::f() through the template parameter. Is there any syntax that allows f() to be called but does not require a template parameter?

+8
c ++ static-methods templates
source share
6 answers

The compiler does not know that A<T>::f() does not use a parameter of type T Therefore, you must provide the compiler with a type every time you use f .

But when I develop a template class, and I notice that some members / methods are independent of the template parameters, I often move them to the base class without templates.

 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 all the same.

+15
source share
  • There is no syntax to indicate this. There is little reason to set the f static method. Instead, make it a free function. If for some reason you have to do this with a static method, implement it in terms of a free function and just name it.
  • Many compilers are likely to do this automatically for you.
+2
source share

No - if you do not want to use the template argument, do not declare the class with the template parameter. If you need a template argument for other members of the class, but it is not needed in f , then move f from the class.

+1
source share

Of course. Give it an alias by assigning it to a function pointer.

+1
source share

No, actually A<int>::f() does not match A<any_other_type>::f() . They are really different. If you want f() truly parameter independent, you can make the class of template A inherit from another class (sometimes called the trait), which offers f() as a static member function:

 struct X { static void f() { ...} }; template <typename T> struct A : X { ... 

Then you can call either A<type>::f() or X::f() .

0
source share

Nice job (if you don't want to use inheritance, and you don't want it to be a non-member function), you can specify the default type for your class:

 template <class T = bool> class A { public: static void f() { cout << "f()" << endl; } }; int main(void) { A<>::f(); return 0; } 

NOTE: this method, however, does not match A<int>::f() or A<long>::f() , etc., but if you do not have a type dependency in the function, then the above may work...

0
source share

Source: https://habr.com/ru/post/649954/


All Articles