如何在Clang中拼接__FUNCTION__与静态字符串?兼容问题解析
FUNCTION 字符串拼接的跨编译器兼容问题
为何仅MSVC支持该写法?
C++标准规定__FUNCTION__是预定义标识符,类型为const char*(左值),并非字符串字面量。而字符串字面量的自动拼接(相邻书写)是标准仅针对字符串字面量的语法特性。
MSVC做了非标准扩展,将__FUNCTION__当作字符串字面量处理,因此允许它与相邻的字符串字面量直接拼接。但Clang严格遵循C++标准,不认可该扩展,所以触发编译错误。
跨编译器兼容的修改方案
方案1:运行时字符串拼接(简单通用)
如果不需要编译时生成静态字符串,直接用std::string的拼接运算符即可,两款编译器均支持:
#include <string> void Test() { auto str = std::string(__FUNCTION__) + "." + "Description"; }
方案2:编译时静态字符串拼接(C++11及以上)
若需要编译时生成静态const char*,可通过constexpr函数实现编译时拼接:
#include <cstddef> // 编译时计算字符串长度 constexpr size_t str_length(const char* s) { size_t len = 0; while (s[len] != '\0') ++len; return len; } // 编译时拼接三个字符串 template<size_t Len1, size_t Len2, size_t Len3> constexpr void concat(char* dest, const char* s1, const char* s2, const char* s3) { size_t idx = 0; while (*s1) dest[idx++] = *s1++; while (*s2) dest[idx++] = *s2++; while (*s3) dest[idx++] = *s3++; dest[idx] = '\0'; } // 封装成宏,方便在函数内使用 #define MAKE_FUNC_DESC() \ []() constexpr { \ constexpr size_t total_len = str_length(__FUNCTION__) + str_length(".") + str_length("Description") + 1; \ char buffer[total_len]; \ concat<str_length(__FUNCTION__), str_length("."), str_length("Description")>(buffer, __FUNCTION__, ".", "Description"); \ return buffer; \ }() void Test() { constexpr auto str = MAKE_FUNC_DESC(); // str 是编译时生成的静态字符数组,可直接作为const char*使用 }
方案3:C++20+ 简洁写法(运行时)
如果项目使用C++20或更高版本,可借助std::format实现更简洁的拼接:
#include <format> void Test() { auto str = std::format("{}.Description", __FUNCTION__); }
内容的提问来源于stack exchange,提问作者M.kazem Akhgary
相关产品推荐
相关产品推荐

