June 2018
Intermediate to advanced
348 pages
8h 45m
English
In the previous example, we saw how a user-defined type can be used to express all the operations done on a built-in type. Another goal of C++ is to write code in a generic manner where we can substitute a user-defined class that mimics the semantics of one of the built-in types such as float, double, int, and so on:
//------------- from SmartValue.cpptemplate <class T>T Accumulate( T a[] , int count ) { T value = 0; for( int i=0; i<count; ++i) { value += a[i]; } return value;}int main(){ //----- Templated version of SmartFloat SmartValue<double> y[] = { 10,20.0,30,40 }; double res = Accumulate(y,4); cout << res << endl;}
Read now
Unlock full access