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

问题描述 投票:-1回答:1

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

编译器难道不应该将“最匹配”的情况用于函数调用吗?我对可变参数模板的理解是,您从上到下,从基本案例到异常。我本来希望在\\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
}
c++ recursion printing variadic-templates
1个回答
2
投票
Vexing parse with:

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

使用

std::stringstream strs{};

std::stringstream strs;

Demo

© www.soinside.com 2019 - 2024. All rights reserved.