0

I am trying to modify the class “calc” to be more generic to accept also doubles or floats.

class calc {
public:
    int multiply(int x, int y);
    int add(int x, int y);
};

int calc::multiply(int k1, int k2)
{
    return k1 * k2;
}

int calc::add(int k1, int k2)
{
    return k1 + k2;
}

This is my implementation below, but I have an error E0441: argument list for class template "calc" is missing (line: calc c;).

template < class T>
class calc
{
public:

    T multiply(T x, T y);
    T add (T x, T y);
};

template < class T>
T calc<T>::multiply(T k1, T k2)
{
    return k1 * k2;
}

template < class T>
T calc<T>::add(T k1, T k2)
{
    return k1 + k2;
}

int main()
{
    calc c;
    std::cout << c.multiply(1, 5);
}

How do I convert the class to be a template class and function?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
CrDS
  • 77
  • 3
  • 8

2 Answers2

2

How is the compiler to know what kind of calc you want? You have to tell it:

calc<int> c;

or

calc<double> c;

or...

TonyK
  • 16,761
  • 4
  • 37
  • 72
1

is a strongly typed language, meaning that you must fully specify all types at declaration. If calc is templated, you cannot declare: calc c as that does not fully specify the type. You must provide the template parameter calc requires to be fully specified, for example:

calc<double> c

TonyK's answer already fully covers this though. I write this to comment that you are reinventing the wheel. The functionality you are writing is already available in the form of:

And these do not require a class. So even if something like: cout << 1 * 5 did not meet your needs and you needed to enact this in the form of a function call by creating a functor object:

multiplies<double> foo;

cout << foo(1, 5);

Live Example

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • That is not what `plus` and `multiplies` are for -- in this context, they are just the same as `+` and `*`. What the OP wants is e.g. a `calc` class that returns a `float` even if both arguments are `int`. – TonyK Nov 28 '18 at 13:49
  • @TonyK The function definitions I was seeing were: `T multiply(T k1, T k2) { return k1 * k2; }` thus exactly matching the signature of `multiplies`, unless I'm misunderstanding something? – Jonathan Mee Nov 28 '18 at 14:16
  • No, they are not the same: `multiplies(3,5)` will return `15`; but `calc::multiply(3,5)` will return `15.0f`. More important, `divides(3,5)` will return `0`; but `calc::divide(3,5)` will return `0.6f`. – TonyK Nov 28 '18 at 14:22
  • @TonyK Well it's a functor, so in looking at it again due to your comment I did catch that mistake :( But when correctly initialized, it does fully replace `calc`. I've added an example in to demonstrate... and make sure that I did it right :J – Jonathan Mee Nov 28 '18 at 14:25