将任意数量的任意类型的值组合为单个字符串的简单命令
Simple command to combine an arbitrary number of values of arbitrary types into a single string
请考虑以下代码。
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;
相关文章:
- 将字符向量转换为单个字符串
- 如何在 c++ 中将 2D 数组转换为单个字符串
- 将单个字符串/字符输入串行监视器
- 查找单个字符串中重复次数最多和次数第二多的字符
- 如何使用 deleteEntry 函数 c++ 删除数组中的单个字符串
- 如何从空格分隔的单个字符串中提取多个子字符串
- 如何比较C++中的单个字符串字符?
- 在 C++98 中写入单个字符串以"线程安全"吗
- 如何将字符串和整数组合成单个字符串 (C++)
- 如何将单个字符串与字符串数组进行比较
- 如何获取从GetPrivateProfileSection()返回的单个字符串
- 将任意数量的任意类型的值组合为单个字符串的简单命令
- 如何在 c++ 中将文件中的段落作为单个字符串读取
- 将字符串数组与用户输入的单个字符串进行比较,它还表明它在该位置找到 2 次
- 在hashmap中搜索,其中键可以是单个字符串或空格分隔的字符串
- 管理单个字符串的内存
- 从字符串中获取单个字符串字符
- 指针——单个字符串与字符串数组
- 在单个字符串中显示Unicode QString的QLatin1String连接
- 如何检查单个字符串输入的部分是int还是char