and*_*dre 2 c++ templates c-strings null-terminated c++03
我有一些遗留函数返回非null终止字符串.
struct legacy {
char a[4]; //not null terminated
char b[20]; //not null terminated
};
Run Code Online (Sandbox Code Playgroud)
我传递了很多这些char数组,我需要一个干净的方法将它们转换为null终止.
截至目前,这就是我在做的事情:
legacy foo;
std::string a(foo.a, sizeof(foo.a));
std::string b(foo.b, sizeof(foo.b));
bar(foo.a.c_str(), foo.b.c_str());
Run Code Online (Sandbox Code Playgroud)
有没有更清洁的方法我可以使用类和模板来减少这些代码...
legacy foo;
bar(make_null_terminated(foo.a), make_null_terminated(foo.b));
Run Code Online (Sandbox Code Playgroud)
这样的事情应该做:
struct make_null_terminated {
template <size_t sz>
make_null_terminated(char (&lit)[sz]) : str(lit, sz) {}
operator const char* () const { return str.c_str(); }
private:
std::string str;
}
Run Code Online (Sandbox Code Playgroud)
这将允许您以您希望的方式使用它.
编辑标签编辑后,我摆脱了std::begin和std::endl.