// Native_templates.cpp : Defines the entry point for the console application. /* __________________________________________________ W O R K I N G W I T H T E M P L A T E S Ron Kessler Created 1/24/2017 __________________________________________________ Native Code Version Run with CTL-F5 A template is analogous to a generic class or function. You can create a generic class or function and use it for all types of data. This save us a lot of coding and a lot of errors. See page 446 in Murach to see how to do the same thing in .Net and managed code. You set it up by declaring a new template and instead of putting in a return type of int/double/whatever, we use a placeholder much like we do in setting up parameters in our functions. So here is a template class that will return a data type. There is a function called Add that takes to values and returns the sum of those values. It can also take 2 strings and it will concatenate those strings. So no matter what we pass to it, that is how it behaves. The code: template T Add(T firstValue, T secondValue) { return firstValue + secondValue; } Look below to see it in action */ #include "stdafx.h" #include #include #include #include using namespace std; //---our template class and the Add function inside of it. template T Add (T firstValue, T secondValue) { return firstValue + secondValue; } //Some people declare these on // one or two lines: // template // T Add (T firstValue, T secondValue) { return firstValue + secondValue; } int main() { string eol = "\n\n"; cout << "Working With Templates" << eol; //---use our template to add 2 numbers int x{ Add (4, 5) }; //substitute values here. Return is an int and we pass in 2 ints cout << "Your sum for two integers is : " << x << eol; double d{ Add (5.5, 6.5) }; cout << "Your sum for two doubles is : " << d << eol; string fName = "Devon "; string lName = "Foster"; string s{ Add (string{ fName }, string{ lName}) }; cout << "Your full name is : " << s << eol; return 0; }