Skip to main content


Showing posts with the label Variadic templates

Variadic template function - Part 1

 In C, we know we have something called printf() function. This printf() function can take any number of arguments of any built-in type (not user-defined type). As an example, the following piece of code is valid for the standard built-in printf() function. <Code> const char* msg = "%s can accept %i parameters (or %s)."; printf(msg, std::string("Variadic templates"), 100, "more"); </Code> The problem in this code is, it will not print the string part, but it gets compiled with the MSVC as well as GCC 8.2 compiler. However, if I change the code like below, now it prints everything properly. <Code> const char* msg = "%s can accept %i parameters (or %s)."; printf(msg, std::string("Variadic templates").c_str() , 100, "more"); </Code> The printf is like a variadic template function but it sticks to only built-in types. Now the question comes how can I write variadic template functions in C++. In C++ 11 the

Variadic template class to add numbers recursively during compilation

 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() {     My