我正在使用受此答案启发的格式功能。只要我通过const char*
它,一切就可以正常工作:
const char* hello = "Hello";
std::string world = "world";
string_format("%s, %s!", hello , world.c_str());
// Returns "Hello, world!"
现在,我在任何地方都使用std :: strings,我想避免.c_str()
在任何地方调用。如何修改此函数以为我调用它,并允许我仅将std :: strings传递给它?
我最终使用了一个中间函数safe
:
#include <iostream>
#include <memory>
#include <iostream>
#include <string>
#include <cstdio>
#include <type_traits>
using namespace std;
template<typename T>
T safe(const T& value)
{return value;}
const char * safe(const string& value)
{return value.c_str();}
template<typename ... Args>
string string_format( const std::string& format, const Args& ... args )
{
size_t size = snprintf( nullptr, 0, format.c_str(), safe(args)... ) + 1; // Extra space for '\0'
unique_ptr<char[]> buf( new char[ size ] );
snprintf( buf.get(), size, format.c_str(), safe(args)... );
return string( buf.get(), buf.get() + size - 1 ); // We don't want the '\0' inside
}
int main()
{
cout<<string_format("%s, %s! %d", "hello", string("world"), 42);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句