I have been given the assignment to make a "calculator" in c++, which takes any number data type as two inputs, calculates either the sum or product, and then logs the equation. All of this using template <typename T>
.
I have a hard time finding documentation to to my specific problems, which are:
- How to setup functions and constructors with the defined return type.
- How to search c++ error log efficiently, so I can fix errors just as easily as in 'C'.
My .hpp file:
#pragma once
#include <sstream>
#include "logger.hpp"
template <typename T>
class Calculator{
public:
Calculator(Logger *l);
T sum(T a, T b);
T multiply(T a, T b);
private:
Logger *logger;
};
My .cpp file:
#include "template_calculator.hpp"
Calculator::Calculator(Logger *l){
logger = l;
}
Calculator::T sum(T a, T b){
T c = a + b;
std::string str_a = std::to_string(a);
std::string str_b = std::to_string(b);
std::string str_c = std::to_string(c);
logger->log(str_a + " + " + str_b + " = " + str_c);
return c;
}
Calculator::T multiply(T a, T b){
T c = a * b;
std::string str_a = std::to_string(a);
std::string str_b = std::to_string(b);
std::string str_c = std::to_string(c);
logger->log(str_a + " * " + str_b + " = " + str_c);
return c;
}
I have tried to follow the guidance of this guy: invalid use of template name without an argument list
.. but it doesn't solve my problems. I get the following errors - all of which I can't fin the solution to.
note: ‘template<class T> class Calculator’ declared here
7 | class Calculator{
error: invalid use of template-name ‘Calculator’ without an argument list
8 | Calculator::T sum(T a, T b){
Attempting to use the advice from above link:
#include "template_calculator.hpp"
template <typename T>
Calculator<T>::Calculator(Logger *l){
logger = l;
}
Calculator<T>::T sum(T a, T b){
T c = a + b;
std::string str_a = std::to_string(a);
std::string str_b = std::to_string(b);
std::string str_c = std::to_string(c);
logger->log(str_a + " + " + str_b + " = " + str_c);
return c;
}
Calculator<T>::T multiply(T a, T b){
T c = a * b;
std::string str_a = std::to_string(a);
std::string str_b = std::to_string(b);
std::string str_c = std::to_string(c);
logger->log(str_a + " * " + str_b + " = " + str_c);
return c;
}
as per:
template<typename T>
LinkedList<T>::LinkedList()
{
start = nullptr;
current = nullptr;
}
And similarly for other member functions.