将任意数量的任意类型的值组合为单个字符串的简单命令

Simple command to combine an arbitrary number of values of arbitrary types into a single string

本文关键字:单个 字符串 组合 简单 命令 任意数 任意 类型      更新时间:2023-10-16

请考虑以下代码。

int id = 666;
stringstream stream(stringstream::in | stringstream::out);
stream << "Object " << id << " active.";
file.write(stream.str());

它组合了所有以<lt;很好地串在一起。我很想发现一个更短、更容易使用、代码重复更少的版本。此外,上面的代码只是一个示例,命令应该接受变量和字符串的任意组合。理想情况下类似于:

int id = 666;
WRITE("Object ", id, " active.");

这在C++中是否可能以可移植的方式实现,即使使用Boost.Preprocessor、内联函数和所有技巧。

您可以在不使用宏进行类型检查的情况下完成此操作:

//filewrite.h
#define WRITE(first, second, third) 
{
   stringstream stream(stringstream::in | stringstream::out);
   stream << first << second << third;
   file.write(stream.str());
}

或者,更清洁,带有模板功能:

template<typename T1, typename T2, typename T3>
void WRITE(T1 const& first, T2 const& second, T3 const& third, fstream& file)
{
   stringstream stream(stringstream::in | stringstream::out);
   stream << first << second << third;
   file.write(stream.str());
}

如果你真的不想进行类型检查,不要使用C++,它是一种静态类型语言!

如果你只是想让它适用于任何类型,可以使用宏(eurgh)或使用可变模板,比如https://gitlab.com/redistd/redistd/blob/master/include/redi/printers.h支持:

#include <redi/printers.h>
using redi::println;
int main()
{
  int id = 666;
  println("Object ", id, " active.");  // write arguments to stdout
}

println函数接受任意数量的参数,并受到Howard Hinnant的一些示例代码的启发,从中无耻地窃取了

很容易将其调整为写入fstream而不是std::cout,例如通过添加

inline
void
fprintln()
{ file << std::endl; }
template<typename T0, typename... T>
  inline
  void
  fprintln(const T0& t0, const T&... t)
  {
    print_one(file, t0);
    fprintln(t...);
  }

然后:

 fprintln("Object ", id, " active.");  // write arguments to 'file'

您不需要(也不需要)宏。这就是模板的设计用于:

template <typename T>
void
write( std::string const& prefix, T const& value, std::string const& suffix )
{
    std::ostringstream fmt;
    fmt << prefix << value << suffix;
    file.write( fmt.str() );
}

另一方面,为什么要麻烦呢?为什么不让客户端代码使用惯用语:

file << prefix << value << suffix;