使用模板可变参数函数将多个参数传递给另一个函数

pass multiple arguments to another function using template variadic function

让我们考虑以下函数:

static void Print(const Type& type, const std::string& message, const std::string& variable) {
    Log(type, message + ": " + variable);
}

我希望它传递任意数量的变量(我的意思是 std::string & 变量——它包含一个变量名),然后通过 Log() 函数一起发送它们,出于这个原因,我考虑过使用模板可变参数函数(重载 Print())。我会这样定义它:

template <typename Arg, typename ...Args)
static void Print(const Type& type, const std::string& message,
                  const Arg& arg, const Args&... args);

然后:

Print(type, message, args...);
Log(type, message + ": " + arg);

只是一个想法,最有可能像这样工作:

我需要做的是以某种方式记住 arg 值,但它需要使用附加参数调用 Print(),我不太喜欢这个想法。你还有其他线索吗?

根据所需的格式,您也许可以使用折叠表达式:

template<class... Args>
void Print(const Type& type, const std::string& message, const Args&... arg)
{
    std::stringstream strstr;
    strstr << message << ": "; // Or your prefix computation, whatever you want.

    ((strstr << arg << ", "), ...);

    std::string toLog = strstr.str();
    // Remove last separator characters.
    toLog.erase(toLog.end() - 2, toLog.end());
    Log(type, strstr.str());
}

Demo

我稍微简化了你的例子,所以假设我正确理解你想做什么,你可以做以下两种解决方案之一,如果你不支持@Max Langhof 建议的 C++17 折叠编译器。

它们都适用于任何支持 operator+ 的类型来做正确的事情,但如果您的 concat 函数是其他东西,则修改起来很简单。

选项 1,递归解包:

template <typename Arg>
static void Print(const Arg& message, const Arg& arg1)
{
    Log(message + ": " + arg1);
}

template <typename Arg, typename... Args>
static void Print(const Arg& message, const Arg& arg1, const Arg& arg2, const Args&... variables)
{
    Print(message, arg1 + ", " + arg2, variables...);
}

选项 2,解包成 std:vector:

template <typename Arg, typename... Args>
static void Print2(const Arg& message, const Arg& arg1, const Args&... variables)
{
    std::vector<Arg> args = { variables... };
    Arg result = std::accumulate(args.begin(), args.end(), arg1, [](const Arg& a, const Arg& b) {
        return a + ", " + b;});
    Log(message + ": " + result);
}

请注意,此版本将在 std::vector 中创建参数的副本,而其他解决方案则不会。

两个示例都可以按以下方式使用:

static void Log(const std::string& m)
{
    std::cout << m << std::endl;
}

int main()
{
    std::string msg = "MyMessage1";
    std::string var1 = "Var1";
    std::string var2 = "Var2";
    std::string var3 = "Var3";
    std::string var4 = "Var4";
    std::string var5 = "Var5";

    Print(msg, var1);
    Print(msg, var1, var2);
    Print(msg, var1, var2, var3);
    Print(msg, var1, var2, var3, var4);
    Print(msg, var1, var2, var3, var4, var5);
}

在我看来,Max Langhof 的解决方案简单而优雅。

不幸的是,它使用仅从 C++17 开始可用的模板折叠。

我提出一个 C++11/C++14 版本,而不是模板折叠,使用初始化未使用数组的老技巧

template <typename ... Args>
void Print (Type const & type, std::string const & message,
            Args const & ... arg)
 {
   using unused = int[];

   std::stringstream strstr;

   strstr << message << ": ";

   (void)unused { 0, (strstr << arg << ", ", 0)... };

    std::string toLog = strstr.str();

    // Remove last separator characters.
    toLog.erase(toLog.end() - 2, toLog.end());
    Log(type, strstr.str());
 }