Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to call a static method of a class template without specifying an instantiation?

Tags:

c++

templates

Is there any way to define a static method in a class template which can be then be called without specifying the instantiation?

I think this could be useful in cases where you have some auxiliary static function, which logically belongs in a class (which happens to be a template one), but doesn't depend on the template parameter.

I don't mind either:

  1. Having the same static method (including address and all) for all instantiations, or
  2. Having a separate static method for each instantiation, but be able to call the static method without specifying an instantiation where I call the method (some default would be called).

e.g.

template<typename T> class C {
public:
    static int func() { return 0; }
};

int main()
{
    // This works.
    return C<int>::func();   

    // These don't work.
    // return C<>::func();   
    // return C::func();   
}
like image 328
Danra Avatar asked Oct 22 '25 15:10

Danra


2 Answers

The simplest solution is probably to have the static function belong in a base class, and then the template derives from the base:

struct CBase {
    static int func() { return 0; }
};

template<typename T> class C : public CBase {
public:
};

int main()
{
    // This works.
    return C<int>::func();

    // This will work too:
    return CBase::func();
}
like image 155
Martin Bonner supports Monica Avatar answered Oct 25 '25 04:10

Martin Bonner supports Monica


You can use inheritance which will also remove the duplication of any non static functions ( that also don't care about the template type ) in your binary, i.e:

class A {
public:
    static int func() { return 0; }
};

template<typename T> 
class B : A {

};
like image 27
Pascal pizza Avatar answered Oct 25 '25 04:10

Pascal pizza