运行C++参数包示例代码时遇collect2.exe链接错误求助
关于C++参数包模板函数编译时未定义引用的问题解答
问题场景
以下是参数包相关示例代码,使用g++ test.cpp -std=c++11编译时出现链接错误:
// template<typename U, typename... Ts> // OK: can deduce U // struct valid; // template<typename... Ts, typename U> // Error: Ts... not at the end // struct Invalid; template<typename... Ts, typename U, typename=void> void valid(U, Ts...); // OK: can deduce U int main() { valid(1.0, 1, 2, 3); // OK: deduces U as double, Ts as {int, int, int} // void valid(Ts..., U); // Can't be used: Ts... is a non-deduced context in this position return 0; }
编译错误信息
c:/program files (x86)/mingw-w64/winlibs-x86_64-posix-seh-gcc-12.2.0-llvm-14.0.6-mingw-w64ucrt-10.0.0-r2/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\86189\AppData\Local\Temp\ccmLsbGr.o:test7.cpp:(.text+0x2b): undefined reference to `void valid<int, int, int, double, void>(double, int, int, int)' collect2.exe: error: ld returned 1 exit status
问题原因与解决方法
原因
代码仅声明了模板函数valid,但未提供任何实现(函数体)。链接器生成可执行文件时,无法找到该模板函数实例对应的具体代码,因此抛出"undefined reference"错误。示例仅用于展示模板参数推导规则,省略了函数实现部分。
解决方法
为模板函数添加定义即可,哪怕是空实现也能满足链接需求。修改后的代码如下:
// template<typename U, typename... Ts> // OK: can deduce U // struct valid; // template<typename... Ts, typename U> // Error: Ts... not at the end // struct Invalid; template<typename... Ts, typename U, typename=void> void valid(U, Ts...) { // 可在此添加函数逻辑,空实现也可正常编译链接 } int main() { valid(1.0, 1, 2, 3); // OK: deduces U as double, Ts as {int, int, int} // void valid(Ts..., U); // Can't be used: Ts... is a non-deduced context in this position return 0; }
内容的提问来源于stack exchange,提问作者Lake_Lagunita
相关产品推荐
相关产品推荐

