我试图了解递归可变参数模板是如何工作的。

#include <iostream>

template<typename T>
static inline void WriteLog(T&& msg) {
    std::wcout << std::forward<T>(msg);
}

template<typename T, typename... Ts>
static void WriteLog(T&& msg, Ts&&... Vals) {
    WriteLog(std::forward<T>(msg));
    WriteLog(std::forward<Ts>(Vals)...);
    std::wcout << "\n**End**";
}

int main() {
    WriteLog("apple, ", "orange, ", "mango");
}

输出:
apple, orange, mango
**End**
**End**

我预计只有一个 **End** 。为什么要打印两次?

最佳答案

调用树:

 WriteLog("apple, ", "orange, ", "mango");
       ->WriteLog("apple, ");
            -> std::wcout << "apple, ";
       ->WriteLog( "orange, ", "mango");
            ->WriteLog("orange, ");
                 -> std::wcout << "orange, ";
            ->WriteLog( "mango");
                 -> std::wcout << "mango";
            ->std::wcout << "\n**End**";
       ->std::wcout << "\n**End**";

关于c++ 11递归可变参数模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30049877/

10-12 17:04