可变参数模板未编译

Variadic template not compiled

本文关键字:编译 变参 参数      更新时间:2023-10-16

代码:

#include <iostream>
template<typename T>    
void out()                   // line 4
{
}
template<typename T, typename... Args>
void out(T value, Args... args)        // line 9
{
    std::cout << value;
    out(args...);    // line 12
}
int main()
{
    out("12345", std::endl);    // line 17
    return 0;
}

构建错误:

g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -pthread -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
../main.cpp: In function ‘int main()’:
../main.cpp:17:24: error: no matching function for call to ‘out(const char [6], <unresolved overloaded function type>)’
../main.cpp:17:24: note: candidates are:
../main.cpp:4:6: note: template<class T> void out()
../main.cpp:4:6: note:   template argument deduction/substitution failed:
../main.cpp:17:24: note:   candidate expects 0 arguments, 2 provided
../main.cpp:9:6: note: void out(T, Args ...) [with T = const char*; Args = {}]
../main.cpp:9:6: note:   candidate expects 1 argument, 2 provided

我希望这个程序给出与std::cout << "12345" << std::endl;模板函数中有什么问题相同的结果?

问题是你把你的无参数版本out是一个模板,如果不显式提供模板参数,就不能调用它。因此

void out() {}
template<typename T, typename... Args>
void out(T value, Args... args) {
    std::cout << value;
    out(args...);
}
int main() {
    out(1, 2.0, "3");
    return 0;
}

按预期工作。

有一个语法错误(错过.),使编译器发疯。

之后,您可能还会遇到out("12345", std::endl)调用的问题,std::endl编译器无法选择的覆盖函数(只需将其转换为static_cast<std::ostream&(*)(std::ostream&)>(std::endl)

此外,out 中的递归以 out() 调用结束,但没有 out 的 0 参数。(另见尤里回答:https://stackoverflow.com/a/20879525/924727)