我已经仔细阅读了可变参数模板的链接器错误,但它似乎并没有解决我的问题。
我有 3 个文件,detail.h,detail.cpp和main.cpp.
其中detail.h只有一行声明了可变参数函数allSame。
//detail.h
bool allSame(unsigned long...);
在detail.cpp中,提供了函数的实现。
//detail.cpp
#include "detail.h"
bool allSame() { return true; }
bool allSame(unsigned long first) { return true; }
bool allSame(unsigned long first, unsigned long second) {
return first == second;
}
bool allSame(unsigned long first, unsigned long second, unsigned long others...) {
if (first == second)
return allSame(first, others);
else
return false;
}
可以很容易地推断,allSame如果其可变参数都相同,则该函数的目的是返回。
//main.cpp
#include "detail.h"
#include <iostream>
int main () {
if (allSame(2, 2, 2, 2))
std::cout << "All same. " << std::endl;
}
在编译和链接上述三个文件(使用 command g++ detail.cpp main.cpp)时,我收到了这个链接器错误
/disk1/tmp/ccTrBHWU.o: In function `main':
main.cpp:(.text+0x1e): undefined reference to `allSame(unsigned long, ...)'
collect2: error: ld returned 1 exit status
确实,我没有提供带有特定签名的重载allSame(unsigned long, ...);但是我确实为函数定义提供了 0、1、2、2+(any) 个参数。也许编译器在函数调用时扩展参数包的方式比我想象的更微妙?
[旁注]如果我将内容移动detail.cpp到detail.h然后程序编译并按预期运行。