简体   繁体   English

当其中一个是函数参数时,在编译时连接 const char

[英]Concatenate const char at compile time when one of them is a function parameter

I'm trying to add a filename prefix to each log string in spdlog.我正在尝试为 spdlog 中的每个日志字符串添加一个文件名前缀。 The Spdlog formatting string looks as this: Spdlog 格式字符串如下所示:

Test log {}

Logs are written as this: spdlog::error("Test log {}", value)日志是这样写的: spdlog::error("Test log {}", value)

I'm trying to wrap this call and concatenate additional {} before formatting string, so I can pass the prefix of the file there.我试图在格式化字符串之前包装这个调用并连接额外的 {},所以我可以在那里传递文件的前缀。

static constexpr char * prefixHolder("{} ");

template<typename... Args>
void critical(const char fmt[], Args&&... args) const
{
    constexpr auto fullFmt = prefixHolder + fmt; //I can't find any solution for this

    spdlog::critical(fullFmt, m_prefix, std::forward<Args>(args)...);
}


Log log("MyClassOrLogger");

log.critical("My format {}", value);

Is it possible to solve this at compile time?有没有可能在编译时解决这个问题? I've tried some approaches, but I haven't found any way to make input fmt argument constexpr for the compiler.我尝试了一些方法,但我还没有找到任何方法来为编译器制作输入 fmt 参数 constexpr。

C++ 17 C++ 17

Any suggestions or solutions?任何建议或解决方案?

Thanks谢谢

Parameter value cannot be used for constexpr.参数值不能用于 constexpr。

You might turn:你可能会转向:

template<typename... Args>
constexpr void critical(const char fmt[], Args&&... args)

into进入

template <char... cs, typename... Args>
void critical(std::integer_sequence<char, cs...>, Args&&... args)
{
    constexpr char fullFmt[] = {'{', '}', ' ', cs... , '\0'};

    spdlog::critical(fullFmt, m_prefix, std::forward<Args>(args)...);
}

to allow to have constexpr char array.允许有 constexpr 字符数组。

ensure-that-char-pointers-always-point-to-the-same-string-literal shows way to create similar sequences from literal string. ensure-that-c​​har-pointers-always-point-to-the-same-string-literal显示了从文字字符串创建类似序列的方法。 In your case, it would be:在您的情况下,它将是:

template <typename Char, Char... Cs>
constexpr auto operator"" _cs() -> std::integer_sequence<Char, Cs...> {
    return {};
}

Usage is then something like:用法是这样的:

log.critical("My format {}"_cs, value); // gcc extension
log.critical(MAKE_SEQUENCE("My format {}"), value);

Demo with gcc extension.带有 gcc 扩展名的演示
Demo with MACRO.使用宏进行演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM