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:
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();
}
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();
}
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 {
};
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