Take the following class:
BasicOperations.h
template<typename T1>
class BasicOperations
{
private:
T1 num;
public:
template<typename T1, typename T2>
BasicOperations() : num(0) {}
template<typename T1, typename T2>
auto addition(T1 num1, T2 num2) -> decltype(T1 + T2) const { return num1 + num2; }
}
I have begun using auto
and from my research found that this is how to declare the function addition
as listed in the above code.
However, when I try to call the method in my Main()
, I cannot figure out the syntax to properly call addition... I have open ended questions, but what exactly is wrong with/ how exactly do I syntactically call the addition
function from my main...
Main.cpp
#include <iostream>
#include "BasicOperations.h"
int main()
{
int x = 10, y = 5;
BasicOperations<int> t(int, int);
//std::cout << t.addition( x, y ) << '\n'; Error: expression must have class type
}
In the main, this
BasicOperations<int> t(int, int);
as said by another user, is meaningless. When using the debugger, it showed as a function declaration, instead of its intended purpose as constructor. Even though local functions can't be defined, they can still be declared. So even thought
exists, it is a function and therefore int.addition()
it can't recognizet
as an object of classBasicOperations
that contains the methodaddition
.Quick fix:
Eliminate
template<typename T1, typename T2>
above default constructor. Also in-> decltype(T1 + T2)
should be changed to-> decltype(num1 + num2)
.When using template constructors, there is no way to explicitly specify the template arguments when calling a constructor template. This means that one cannot write:
BasicOperations<int> t<int,int>();
Instead, the types of the templates must be deduced through argument deduction. However, the constructor in the code takes no arguments, that is why
BasicOperations<int> t(int,int);
is read as a function declaration instead.