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

标签 c++ c++11 templates variadic-templates variadic-functions

让我们考虑以下函数:

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);

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

  • args...将通过并且Print()函数将被递归调用,直到没有参数为止,
  • 但与此同时,Log()函数将被调用,基本上每次都会记录它。

我需要做的是以某种方式记住 arg值,但需要调用 Print()有一个额外的论点,我真的不喜欢这个想法。你还有其他线索吗?

最佳答案

在我看来,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());
 }

关于c++ - 使用模板可变参数函数将多个参数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51761209/

相关文章:

c++ - 具有路径重建的 Floyd–Warshall 算法找不到路径

c++ - 特征表达式模板比指数的手动循环慢

c++ - CMake 使库需要 cxx 标准

C++ 静态多态性 (CRTP) 和使用派生类的 typedef

c++ - 如何确定一个类型是否可以仅使用 const 引用调用?

c++ - 当它应该是字符串时输入接受字符?

c++ - 直接从 C++0x lambda 调用方返回

c++ - 为什么标准不允许在模板参数列表中初始化常量依赖类型?

php - 关键未捕获错误 : Call to a member function is_on_sale() on null in Woocommerce

c++ - T::* 在模板参数中是什么意思?