c++ 使用函数模板进行函数重载

icnyk63a  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(182)

我试图在遵循DRY原则的情况下重载一个函数。重载之间唯一的区别是参数类型,所以我选择使用模板。我基本上得到了以下代码:
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;
}

此代码产生链接错误:

/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

令人惊讶的是,当不使用显式示例化时,会发生奇怪的链接错误:

/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

为什么会出现这些错误?如何修复代码?
我使用GCC 11.3.0和-Wall -Wextra -std=c++17标志。

zzwlnbp8

zzwlnbp81#

我错过了void func(std::vector<double>&)void func(std::vector<int>&)函数的inline说明符,因为它们的定义在头文件中。感谢@DrewDormann和@Eljay!

相关问题