0

I would like to make a general function that will take two parameters of any data type (although they will always be some sort of a number) and then multiply them together, round them down, and return their value as an integer.

I've created a template function, but I would like some feedback regarding the function. Will it work in all cases with values containing short, int, float, decimal, etc? If not how can I change it to do so?

// Header File
class MathFunctions
{
public:
   template<typename A, typename B>
   static int MultiplyToInt(
      const A const& base,
      const B const& multiplier);
};

// CPP File
#include "MathFunctions.h"

template<typename A, typename B>
int MathFunctions::MultiplyToInt(
   const A const& base,
   const B const& multiplier)
{
   return static_cast<int>(floor(base * multiplier));
}

// Sample code to run the function
float value = 0.82;
const int result = MathFunctions::MultiplyToInt<int, float>(10, value);

Result should hold the value 8, but if the parameters were that of a decimal, float, int, long, short, etc... it should still be able to work as expected.

Rick
  • 97
  • 1
  • 8
  • Remember that templates must be fully visible to anyone who needs to use it. Without the full "blueprint" being expanded somewhere the linker can find, there will be linker errors. Implementing the guts of a template in a cpp file usually leads to [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – user4581301 Jun 27 '19 at 22:50

1 Answers1

0

What is the signature of the function floor? You are trusting that the compiler will know how to implicitly cast the results of T * T. That is the first problem.

Secondly, you'll need to know if T supports the operator '*'. See here for details on that: Is it possible to write a template to check for a function's existence? and How to check whether operator== exists?