First time at GK Digital?

GK Digital is an online, collaborative learning platform built from the ground up to be a superior learning experience on the web. It is self-paced and supported by instructors and peers. GK Digital is professional training in the 21st century, from Global Knowledge.
Task: Create generic classes and functions with templates
Tags:
C++

When implementing algorithms and data structures it is common to write multiple pieces of code that are identical except for the types involved.

Below is a classic example of a math function that is essentially independent of the data type; notice that the algorithm code is repeated in the two functions while the type names differ.

int    max(int    a, int    b) { return a > b ? a : b; }
double max(double a, double b) { return a > b ? a : b; }

Container types are another rich source of type-independent code. Below is a classic example where the storage algorithm is identical while the type of data varies.

class StackOfInt
{
  int* _values;
  int  _capacity;
  int  _count;
  
public:
  void push(int value);  
  int  pop();
};

class StackOfDouble
{
  double* _values;
  int     _capacity;
  int     _count;
  
public:
  void   push(double value);
  double pop();  
};

Without direct language support it is very difficult to eliminate the repeated code from these examples: algorithms with repeated code are difficult to maintain and containers that store base-class pointers lose type information and require extensive use of casts.

C++ templates provide an elegant way to handle generic functions and generic classes. The algorithms and containers are coded once and the compiler instantiates the templates for each client type as needed.

System.InvalidOperationException: The model item passed into the dictionary is of type 'LearningLine.Interface.ICourse[]', but this dictionary requires a model item of type 'LearningLine.Mongo.Course[]'. at System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) at System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) at System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) at RazorGenerator.Mvc.PrecompiledMvcView.Render(ViewContext viewContext, TextWriter writer) at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection) at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model) at ASP._Views_Tasks_ShowPublic_cshtml.Execute()

Preview any course on GK Digital for free.

Just choose a course from our catalog and then press preview course for free.