0
template <typename T>
T smaller(T a, T b)
{
    if (a < b)
    {
        return a;

    }
    return b;
}

/*This template receives will work only for the function with two parameters. What if I have to create one template which accepts any number of parameters? */

  • you might want to look into variadic templates and fold expressions – Mohammed Li Aug 23 '22 at 17:42
  • ... which are discussed, in length, in every C++ textbook covering modern C++. – Sam Varshavchik Aug 23 '22 at 17:43
  • In relation to the dupes: Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Aug 23 '22 at 17:43
  • What should the boolean logic be if you supply 3 arguments? `return a < b && b < c;`? Something else? – Ted Lyngmo Aug 23 '22 at 17:43
  • 2
    Side-note: This is not a case where a variadic template would do you much good; there's no great optimizations to be made when the compiler knows at compile-time how many items it will be scanning, so all this does is end up spawning a copy of the code for each unique count of elements for each unique `T`, bloating the program for no significant benefit. You probably just want to follow the pattern seen with `std::min`, which accepts a `std::initializer_list` (which also allows it to optionally accept a comparator function as the second argument). Or just use `std::min` in the first place... – ShadowRanger Aug 23 '22 at 17:46

0 Answers0