以下代码效果很好(示例来自cppreference.com):
class SomeClass
{
public:
void tprintf(const char* format) // base function
{
std::cout << format;
}
template<typename T, typename... Targs>
void tprintf(const char* format, T value, Targs... Fargs) // recursive variadic function
{
for (; *format != '\0'; format++) {
if (*format == '%') {
std::cout << value;
tprintf(format + 1, Fargs...); // recursive call
return;
}
std::cout << *format;
}
}
};
void main()
{
SomeClass someClass;
someClass.tprintf("% world% %\n", "Hello", '!', 123);
}
当我尝试通过创建SomeClass类的lib来复制它时,我得到一个未解析的外部符号错误:
class SomeClass
{
public:
void tprintf(const char* format);
template<typename T, typename... Targs>
void tprintf(const char* format, T value, Targs... Fargs);
}
void SomeClass::tprintf(const char* format) // base function
{
std::cout << format;
}
template<typename T, typename... Targs>
void SomeClass::tprintf(const char* format, T value, Targs... Fargs) // recursive variadic function
{
for (; *format != '\0'; format++) {
if (*format == '%') {
std::cout << value;
tprintf(format + 1, Fargs...); // recursive call
return;
}
std::cout << *format;
}
}
#include <ibppWrapper.h>
void main()
{
SomeClass someClass;
someClass.tprintf("% world% %\n", "Hello", '!', 123);
}
error LNK2019: unresolved external symbol "public: void __thiscall SomeClass::tprintf<char const *,char,int>(char const *,char const *,char,int)" (??$tprintf@PBDDH@SomeClass@@QAEXPBD0DH@Z) referenced in function _main
似乎链接器正在我的SomeClass lib中搜索具有确切参数的函数:
SomeClass::tprintf<char const *,char,int>(char const *,char const *,char,int)
虽然它应该找到或搜索:
SomeClass::tprintf<T,... Targs>(char const *,T, ... Targs)
我的结论是否正确? 这是预期的行为吗? 有解决方案吗?