4 Function Template

1 minute read

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 T with 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() with char*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 static in header file, and inline if 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, in func1.o, the compiler puts the definition of Max() for int Do the same at func2.cpp

When linking, how is it not a duplicate definition?

In the object dumps,

  • func1 is renamed as _Z5func1ii in cpp due to overloading
    • Encodes its parameters ii
  • Linker is aware that the Max() are duplicates, and throws one of them out
    • WEAK binding (may have multiple instances)
    • GLOBAL binding in normal functions
    • LOCAL binding for static functions (only in current object)