I'm trying to overload a function while adhering to the DRY principle. The only difference between overloads are argument types, so I chose to use templating. I came up with essentially the following code:
a.h
:
#ifndef A_H
#define A_H
#include <vector>
template<typename T>
void func(std::vector<T>& vec);
void func(std::vector<double>& vec) { func<double>(vec); }
void func(std::vector<int>& vec) { func<int>(vec); }
void otherfunc();
#endif // A_H
a.cc
:
#include "a.h"
template<typename T>
void func(std::vector<T>& vec)
{
vec.resize(10);
}
void otherfunc()
{
std::vector<double> x;
func(x);
}
template void func<double>(std::vector<double>&);
template void func<int>(std::vector<int>&);
main.cc
:
#include "a.h"
int main()
{
otherfunc();
return 0;
}
This code produces a linking error:
/nix/store/y5jcw4ymq7qi735wbm7va9yw3nj2qpb9-binutils-2.39/bin/ld: /run/user/1000/cc6xxYLN.o: in function `func(std::vector<double, std::allocator<double> >&)':
main.cc:(.text+0x0): multiple definition of `func(std::vector<double, std::allocator<double> >&)'; /run/user/1000/ccUyR0Cy.o:a.cc:(.text+0x0): first defined here
/nix/store/y5jcw4ymq7qi735wbm7va9yw3nj2qpb9-binutils-2.39/bin/ld: /run/user/1000/cc6xxYLN.o: in function `func(std::vector<int, std::allocator<int> >&)':
main.cc:(.text+0x10): multiple definition of `func(std::vector<int, std::allocator<int> >&)'; /run/user/1000/ccUyR0Cy.o:a.cc:(.text+0x80): first defined here
collect2: error: ld returned 1 exit status
Surprisingly, when not using explicit instantiation, weird link errors occur:
/nix/store/y5jcw4ymq7qi735wbm7va9yw3nj2qpb9-binutils-2.39/bin/ld: /run/user/1000/ccpXFxFV.o: in function `func(std::vector<double, std::allocator<double> >&)':
main.cc:(.text+0x0): multiple definition of `func(std::vector<double, std::allocator<double> >&)'; /run/user/1000/ccMYxyNR.o:a.cc:(.text+0x0): first defined here
/nix/store/y5jcw4ymq7qi735wbm7va9yw3nj2qpb9-binutils-2.39/bin/ld: /run/user/1000/ccpXFxFV.o: in function `func(std::vector<int, std::allocator<int> >&)':
main.cc:(.text+0x10): multiple definition of `func(std::vector<int, std::allocator<int> >&)'; /run/user/1000/ccMYxyNR.o:a.cc:(.text+0xc0): first defined here
/nix/store/y5jcw4ymq7qi735wbm7va9yw3nj2qpb9-binutils-2.39/bin/ld: /run/user/1000/ccpXFxFV.o: in function `func(std::vector<double, std::allocator<double> >&)':
main.cc:(.text+0x1): undefined reference to `void func<double>(std::vector<double, std::allocator<double> >&)'
/nix/store/y5jcw4ymq7qi735wbm7va9yw3nj2qpb9-binutils-2.39/bin/ld: /run/user/1000/ccpXFxFV.o: in function `func(std::vector<int, std::allocator<int> >&)':
main.cc:(.text+0x11): undefined reference to `void func<int>(std::vector<int, std::allocator<int> >&)'
collect2: error: ld returned 1 exit status
Why do these errors occur? How the code can be fixed?
I'm using GCC 11.3.0 with -Wall -Wextra -std=c++17
flags.