Why function template can exist in multiple source files

54 views Asked by At

I know the one definition rule and why the function definition should not be put in the header file if you want to use it in multiple source files.

However, I don't quite get the reason why we can put the function template in the header file. During the compile time, the compiler creates an instantiation. Now aren't there still two function definitions for "int sum(int, int)" for each translation unit as the example below.

// main.cpp
include "helper.hpp"

int main() {
    sum(2, 3);
    return 0;
}

// helper.hpp
template <typename T>
T sum(T a, T b) {
    return a + b;
}

// helper.cpp
#include "helper.hpp"

int sum2(int a, int b)
{
    return sum(a, b);
}
1

There are 1 answers

4
6502 On

Just because the standard says so.

Template would not be practically usable otherwise, so they can work that way (and for example if in the template body implementation you use a static variable, there must be only one of those static for each instantiation (e.g. one for int and a separate one for float).

C++ is a mixed bag of weird rules: e.g. you cannot call a function without first seeing its prototype... except in the class where you can call methods even if they're defined later in the class. Why does that work? Just because the standard says so.

Don't try to look too hard into logic reasons, there are none. Just learn the rules... and don't try too much on guessing, intuition is not a good guide in C++.