C++ templates

I have the following template codes but some normal functions too and want
to group them together.

I usually put the implementation of templates in an .ipp file. What would be a good scheme for the normal functions. Put their implementations in a .cpp file, or leave them in the .ipp file?

#ifndef NUMERIC_HPP
#define NUMERIC_HPP

#include <iostream>
#include <malloc.h>
#include <iomanip>
#include <cstdlib>
#include <string.h>

using namespace std;

template <class T>
inline T  
abs 
(
 T  v
 );

template <class T>
inline T  
sqr 
(
 const T  r
 ) ;

inline bool  
odd 
(
 int  i
 ) {
  
  return (i & 0x1);  //  Bitwise AND, (0101 & 0001) returns true.
  
}

inline bool  
even 
(
 int  i
 ) {
  
  return ( ! (i & 0x1) );  //  Bitwise AND, (0101 & 0001) returns true.
  
}

inline long int  
mem 
(
 );

inline void  
randomize 
(
 );

inline float  
rand 
(
   const float  max
 );

inline int  
rand
(
   const int  max
 );

#include "tomso/numeric/impl/numeric.ipp"

#endif

Inline function definitions belong in a header, external function definitions belong in a .cpp.

Is it possible to have the following two functions as a template for both integer and float?

inline float
rand 
(
 const float  max
 ) {

  return ( max * ((float) rand () / (float) RAND_MAX) );

}

inline int 
rand
(
 const int  max
 ) {

  return ( (int) floor (max * ((float) rand () / (float) RAND_MAX)) );

}


That logic doesn't work for integers because rand() / RAND_MAX just becomes zero. You don't need floor either, you just can take the remainder with %, which calculates like this:

0 % 10 = 0
1 % 10 = 1
2 % 10 = 2
3 % 10 = 3
4 % 10 = 4
5 % 10 = 5
6 % 10 = 6
7 % 10 = 7
8 % 10 = 8
9 % 10 = 9
10 % 10 = 0
11 % 10 = 1
...

...so rand() % max gets you a number between 0 and max-1, as long as max is significantly smaller than RAND_MAX.

int random(int max) { return(rand() % max); }

Your logic looks reasonable for float however. Again, max should be much smaller than RAND_MAX.

1 Like