The idea of having a class to add numbers (variable parameters) during compilation time recursively. Also wanted to restrict types to a single type while sending parameters to class member function. That said, if we mix int, float and double types to add function shall result in compilation error. How do we achieve this.
The below is the code which actually helps to achieve this:
<code>
#include <fmt/format.h>
template<typename T>
class MyVarSumClass{
private:
T _sum = 0;
public:
template<typename... TRest>
T add(T num, TRest... nums){
static_assert(std::conjunction<std::is_same<TRest, T>...>{}); /* Assert fails
if types are different */
_sum += num;
return add(nums...); // Next parameter packs gets picked recursively
}
// Base case
T add(T num){
_sum += num;
return _sum;
}
};
int main()
{
MyVarSumClass<float> objAdd;
fmt::print("{}\n", objAdd.add(1.1f,1.2f,1.3f,1.4f,1.5f));
return 0;
}
</code>
Comments