c++ 将 std::source_location::function_name() 作为字符串文字模板参数传递

问题描述 投票:0回答:1

我有这段代码,它返回编译时由

__PRETTY_FUNCTION__
宏提供的修改后的函数名称字符串:

template<size_t N>
struct SL
{
    char value[N];
    constexpr SL(const char (&str)[N])
    {
        for(size_t i = 0; i != N; ++i)
            value[i] = str[i];
    }
};

template<SL literal>
consteval auto PrettifyFunctionName()
{
    ...
}

我这样使用它:

constexpr auto resultName = PrettifyFunctionName<__PRETTY_FUNCTION__>();

我想将宏

__PRETTY_FUNCTION__
替换为
std::source_location::function_name()
我如何将它作为模板参数传递?
还有另一种方法可以将其作为 PrettifyFunctionName 中的
constexpr
值吗?

c++ templates constexpr
1个回答
0
投票

添加一个从

const char*
复制到数组中的构造函数到
SL
,然后:

constexpr auto funcName = std::source_location::current().function_name();
constexpr auto resultName = PrettifyFunctionName<SL<mystrlen(funcName)+1>(funcName)>();

您需要自己定义

mystrlen
strlen
等效,因为
std::strlen
未标记为
constexpr

© www.soinside.com 2019 - 2024. All rights reserved.