【问题标题】:how to write variadic function for any number of string concatenation in c++如何在 C++ 中为任意数量的字符串连接编写可变参数函数
【发布时间】:2017-08-23 07:47:11
【问题描述】:

我是 C++ 的新手。我知道这是一个非常常见的问题,但我想要一个完整的代码来连接任意数量的字符串,这些字符串传递给 c++ 中的函数。我将函数调用为:

string var1,var2;
var1=concat_string("one","two");
cout<<var1<<endl;
var2=concat_string("one","two","three");
cout<<var2<<endl;

我需要的输出是:

onetwo
onetwothree

我已经阅读了可变参数函数,但我尝试了以下代码来连接字符串,而不用担心结果大小和字符串参数的数量。我的代码是:

#include <cstdarg>
template<typename... T>
string concat_string(T const&... t){
    std::stringstream s;
    s<<t;
    return s;
}

但是我在这段代码中有很多错误。如何更正我的代码。谢谢..

【问题讨论】:

  • 你可以简单地做std::string("one")+"two"+"three";我不认为这是一个常见的问题,因为你不需要这样的功能......这是一个练习吗?
  • @tobi303 感谢您提供简单而好的解决方案。它工作正常。但实际上我只是想学习字符串连接的可变参数函数过程,以便我可以将这个过程应用到其他一些应用程序中。

标签: c++ string-concatenation variadic


【解决方案1】:

在 C++17 中,使用折叠表达式,它会是

template<typename... Ts>
string concat_string(Ts const&... ts){
    std::stringstream s;
    (s << ... << ts);
    return s.str();
}

以前(但自 C++11 起),您必须依靠一些技巧来获得有效的扩展上下文,例如:

template<typename... Ts>
string concat_string(Ts const&... ts){
    std::stringstream s;
    int dummy[] = {0, ((s << ts), 0)...};
    static_cast<void>(dummy); // Avoid warning for unused variable
    return s.str();
}

【讨论】:

【解决方案2】:

由于您似乎正在学习 C++11,因此这里是 @Jarod42 支持 perfect forwarding 的出色解决方案的一个小扩展:

template <typename... T>
std::string concat_string(T&&... ts) {
  std::stringstream s;
  int dummy[] = { 0, ((s << std::forward<T>(ts)), 0)... };
  static_cast<void>(dummy); // Avoid warning for unused variable
  return s.str();
}

完美的转发和右值引用是 C++11 中另一个可以提高性能的特性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-15
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多