为什么我的递归可变参数模板没有编译?

Why is my recursive variadic template not compiling?

我想更好地理解可变参数模板,这就是为什么我编写了一个函数,它接受任意数量的参数,将它们转换为字符串,将它们添加到字符串流并打印该流。我的期望是编译器从 \1 跳到 \2 再到 \3 再到 \4 再到 \5 (比较代码)。但相反,它停留在 \2。这是为什么?

编译器不应该将 "most matching" 这种情况用于函数调用吗?我对可变参数模板的理解是从上到下,从基本情况到异常。我本以为,在 \2 中,当调用 print(strs, "this", " is ", "a ", "test ", 1, 2, 'a') 时,它会转到 \3

Play with this code.

#include <string>
#include <iostream>
#include <sstream>


void print(std::string msg) // 5
{
    std::cout << msg;
}

template <class T>
void print(std::stringstream &strs, T t) // 4
{
    strs << std::to_string(t);
    print(strs.str());
}

template <class... Args, class T>
void print(std::stringstream &strs, T t, Args... args) // 3
{
    strs << t;
    print(strs, args...);
}

template <class... Args>
void print(Args... args) // 2
{
    std::stringstream strs();
    print(strs, args...);
}

int main()
{
    print("this", " is ", "a ", "test ", 1, 2, 'a'); // 1
}

令人烦恼的解析:

std::stringstream strs(); 函数声明

使用

std::stringstream strs{};

std::stringstream strs;

Demo