variadic class template c++ code example

Example 1: c++ class template

#include <vector>

// This is your own template
// T it's just a type
template <class T1, class T2, typename T3, typename T4 = int>
class MyClass
{
  public:
  	MyClass() { }
  
  private:
  	T1 data; 		// For example this data variable is T type
  	T2 anotherData;	// Actually you can name it as you wish but
  	T3 variable;	// for convenience you should name it T
}

int main(int argc, char **argv)
{
  std::vector<int> array(10);
  //          ^^^
  // This is a template in std library
  
  MyClass<int> object();
  // This is how it works with your class, just a template for type
  // < > angle brackets means "choose" any type you want
  // But it isn't necessary should work, because of some reasons
  // For example you need a type that do not supporting with class
  return (0);
}

Example 2: variadic templates

template<class... Args>
void Foo(Agrs*... arguments);

template<class... Args>
class A;

/* Variadic templates can be used to allow a multitude of variations
of a class or function to be compiled without having to explicitly
state what the required amount of template parameters are.

In order to use the parameter pack you need to unpack it. This can be
done through C++17 fold expressions or using recursion:*/

template<typename Arg>
void Foo(Arg* arg)
{
  // do something.
}

template<typename Arg, typename... Args>
void Foo(Arg* arg, Args*... args)
{
  Foo(arg);
  Foo(args);
}

Tags:

Cpp Example