有没有任何方法可以将varargs与boost::格式一起使用

Is there any way to use varargs with boost::format?

本文关键字:boost 格式 一起 varargs 方法 任何 有没有      更新时间:2023-10-16

我有点讨厌使用固定大小的缓冲区和vnsprintf常见的怀疑。

像这样的东西是否可以使用boost::format来处理变量参数列表?

遗憾的是,我不能使用C++11中的任何东西。

void formatIt(const char* msg, ...) {
        va_list args;
        va_start(args, msg);
        boost::format f(msg);
        for loop somehow {                  
          f % va_arg(args, const char *);   //does this work?           
        }
        va_end(args);
}

我使用这个:

inline static std::string FormatStringRecurse(boost::format& message)
{
    return message.str();
}
template <typename TValue, typename... TArgs>
std::string FormatStringRecurse(boost::format& message, TValue&& arg, TArgs&&... args)
{
   message % std::forward<TValue>(arg);
   return FormatStringRecurse(message, std::forward<TArgs>(args)...);
}
template <typename... TArgs>
std::string FormatString(const char* fmt, TArgs&&... args)
{
    using namespace boost::io;
    boost::format message(fmt);
    return FormatStringRecurse(message, std::forward<TArgs>(args)...);
}

我曾经使用过这个:

inline static std::string FormatString()
{
    return std::string();
}
inline static std::string FormatString(const char* szMessage)
{
    return szMessage;
}
template<typename Type1>
static std::string FormatString(const char* formatString, const Type1& arg1)
{
    using namespace boost::io;
    boost::format formatter(formatString);
    formatter % arg1;
    return boost::str( formatter );
}
template<typename Type1, typename Type2>
static std::string FormatString(const char* formatString, const Type1& arg1, const Type2& arg2)
{
    using namespace boost::io;
    boost::format formatter(formatString);
    formatter % arg1 % arg2;
    return boost::str( formatter );
}
template<typename Type1, typename Type2, typename Type3>
static std::string FormatString(const char* formatString, const Type1& arg1, const Type2& arg2, const Type3& arg3)
{
    using namespace boost::io;
    boost::format formatter(formatString);
    formatter % arg1 % arg2 % arg3;
    return boost::str( formatter );
}
/// etc up to 10 args

我想它没有按照你的要求使用varargs,但你经常需要超过10个左右的参数吗?可能有一些宏观魔法会让你想要的事情发生,但呃。。。这很神奇,所以你最好把所有的版本都写出来。