Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static non templated function in templated class

First, I'm not realy having a problem, but I like to keep things as simple as possible. I'm using a templated class named Math and besides a lot of other stuff there are random functions.

Different types of random functions, and a function to set the random seed. So every function except the seed function uses the type class Real. But when I want to set the seed I have to pass some random (haha) type to be able to call the function:

Math<u32>::SeedRandom(System::time());

Again this is not a real problem, but I'm curious if it's possible to get the same result without the need to use the <u32>.

Here a snippet from the Math class:

template <class Real>
class Math
{
public:
    static void SeedRandom(u32 seed) { srand(seed); }
    static Real UnitRandom() { return (Real)((f64)rand() / (f64)RAND_MAX); }
};

btw. f64 is typedef'd to double and u32 to unsigned int.

like image 804
v01pe Avatar asked Feb 10 '12 11:02

v01pe


2 Answers

Static functions should be called by ClassName::FunctionName. Because ClassName is a template, you have to specify template arguments. Static functions can also be called on an object, i.e. object.StaticFunctionName, so if you have an object already, you can avoid specifying template arguments, but in my personal biased opinion calling a static function on an object is ugly.

What I'd do if I were you is to make the function a nonmember one (friend to the template, if needed), in the same namespace as your class.

like image 70
Armen Tsirunyan Avatar answered Nov 15 '22 03:11

Armen Tsirunyan


There's no way to make the function callable as Math::SeedRandom (except making Math non-templated of course). The best you could do is move SeedRandom into a separate, non-templated class or just live with calling it as Math<whatever>::SeedRandom.

like image 33
sepp2k Avatar answered Nov 15 '22 03:11

sepp2k