C ++中的命名参数字符串格式化 [英] Named parameter string formatting in C++
问题描述
我想知道是否有一个类似Boost格式的库,但支持命名参数,而不是位置。这是一个常见的成语。 Python,你有一个上下文来格式化字符串,可能使用或不使用所有可用的参数,例如
I'm wondering if there is a library like Boost Format, but which supports named parameters rather than positional ones. This is a common idiom in e.g. Python, where you have a context to format strings with that may or may not use all available arguments, e.g.
mouse_state = {}
mouse_state['button'] = 0
mouse_state['x'] = 50
mouse_state['y'] = 30
#...
"You clicked %(button)s at %(x)d,%(y)d." % mouse_state
"Targeting %(x)d, %(y)d." % mouse_state
有没有任何库提供最后两行的功能?我希望它提供一个API类似:
Are there any libraries that offer the functionality of those last two lines? I would expect it to offer a API something like:
PrintFMap(string format, map<string, string> args);
在Googling中,我发现许多库提供了位置参数的变体,但没有一个支持命名的。理想情况下,库有很少的依赖,所以我可以轻松放入我的代码。 C ++不会像收集命名参数一样习惯,但是可能有人比我想象的更多。
In Googling I have found many libraries offering variations of positional parameters, but none that support named ones. Ideally the library has few dependencies so I can drop it easily into my code. C++ won't be quite as idiomatic for collecting named arguments, but probably someone out there has thought more about it than me.
性能很重要,特别是我喜欢保持内存分配下降(总是棘手的C ++),因为这可以在没有虚拟内存的设备上运行。
Performance is important, in particular I'd like to keep memory allocations down (always tricky in C++), since this may be run on devices without virtual memory. But having even a slow one to start from will probably be faster than writing it from scratch myself.
推荐答案
答案似乎是: ,没有,没有一个C ++库这样做,而C ++程序员显然甚至不需要一个,基于我收到的意见。我必须再写一遍。
The answer appears to be, no, there is not a C++ library that does this, and C++ programmers apparently do not even see the need for one, based on the comments I have received. I will have to write my own yet again.
这篇关于C ++中的命名参数字符串格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!