函数采用可变参数模板包将std :: strings转换为const char *?

瓦伦丁

我正在使用受此答案启发的格式功能只要我通过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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章