Presentation is loading. Please wait.

Presentation is loading. Please wait.

Anatomy of Templates CSCE 121 J. Michael Moore

Similar presentations


Presentation on theme: "Anatomy of Templates CSCE 121 J. Michael Moore"— Presentation transcript:

1 Anatomy of Templates CSCE 121 J. Michael Moore
Including content created by Bjarne Stroustrup and Jennifer Welch.

2 Function template <typename TypeName1, typename TypeName2> Typename1 genericFunction(const TypeName1& t1, const TypeName2& t2) { Typename1 temp1; Typename2 temp2; // ... } template <typename TypeName> void otherFunction(TypeName& t) {

3 Class template <typename TypeName> class MyClass { Typename val; public: void setVal(Typename newVal); } template <typename Typename> void MyClass::setVal(const Typename& newVal) { val = newVal;

4 Class template <typename T> class MyClass { T val; public: void setVal(T newVal); } void MyClass::setVal(const T& newVal) { val = newVal;

5 Notes Problems: Recommendation: poor error diagnostics (but improving)
delayed error messages (often at link time) all templates must be fully defined in each translation unit (so put everything, including function definitions, in header files) Recommendation: use template-based libraries (e.g., vector) don’t try to do anything fancy yourself (yet) use pass by reference and pass by constant reference


Download ppt "Anatomy of Templates CSCE 121 J. Michael Moore"

Similar presentations


Ads by Google