4 Function Template
Published:
int Max(int x, int y)
return x > y ? x : y;
std::string Max(std::string x, std::string y);
return x > y ? x : y;
CPP allows templates for the same implementation, so you don’t have to repeat
template <typename T>
T Max(T x, T y)
return x > y ? x : y;
const T& Max(const T& x, const T& y);
// better
Above is not actual cpp code. The compiler generates from the template
- Figure out the actual type, and replace
Twith it - Better write with
const T&, since not modifying
Need definition in header file, not in another cpp file, since it has to be seen at compile time
Template Overloading
But if use Max("AAA", "BBB"), will fail, since comparing two pointers, unpredictable
- Compiler generates a version of
Max()withchar*s
Want a template that specializes the type by giving a concrete definition for certain types
const char* Max(const char* x, const char* y)
return strcmp(x, y) > 0 ? x : y;
- Even if you declare this specialization, the compiler will stop using the
template
Make it
staticin header file, andinlineif short
Compilation
Build a wrapper func1() around Max() in func1.cpp
#include "max.h"
// wrappers on Max() template
int func1(int x, int y) // defined for int
return Max(x, y);
int func2(int x, int y)
return Max(x, y);
- When
func1.cpp, infunc1.o, the compiler puts the definition ofMax()forintDo the same atfunc2.cpp
When linking, how is it not a duplicate definition?
In the object dumps,
func1is renamed as_Z5func1iiin cpp due to overloading- Encodes its parameters
ii
- Encodes its parameters
- Linker is aware that the
Max()are duplicates, and throws one of them outWEAKbinding (may have multiple instances)GLOBALbinding in normal functionsLOCALbinding forstaticfunctions (only in current object)
