可以在constexpr中获得`__func__`的值吗?

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

我有一个用__func__调用构造函数的宏。是否可以将其转换为constexpr并仍然使用func的“本地”/“正确”版本?

#define LOG_SCOPE_DURATION(category_arg) \
  ScopeDuration __scopeDuration = ScopeDurationConstructor(category_arg, __func__);
c++ macros constexpr
2个回答
1
投票

如果您使用的是C ++ 17或之前,则无法将宏转换为函数。您可以获得的最接近的是创建一个接受该位置并使用它的函数。

请注意,宏可以为您创建内联变量,函数永远不会将任何变量添加到当前堆栈帧。因此,您可以将[[nodiscard]]添加到函数中,以忽略您的返回值。

template<typename T>
[[nodiscard]] constexpr ScopeDuration createScopeDuration(T &&t, const char *location)
{
    return ScopeDurationConstructor(std::forward<T>(t), location);
}
#define LOG_SCOPE_DURATION(category_arg) NS::createScopeDuration(category_arg, __func__)

用法:

 auto scope = LOG_SCOPE_DURATION(argument);

这基本上是ScopeDurationConstructor函数。

希望从C ++ 20开始,你可以使用std::source_location,这是constexpr。在这种情况下,你可以写:

template<typename T>
[[nodiscard]] constexpr ScopeDuration createScopeDuration(T &&t, const std::source_location& location = std::source_location::current()))
{
    return ScopeDurationConstructor(std::forward<T>(t), location.function_name());
}

用法:

auto scope = createScopeDuration(argument);

同样,您可以将此全部包含在ScopeDuration的构造函数中。

请注意,此功能已被批准用于C ++ 20,但是,该标准尚未添加到标准中。有关详细信息,请参阅trip report


2
投票

有可能在constexpr中获得__func__的价值吗?

是。

是否可以将[my macro]转换为constexpr?

不。如果你在constexpr函数中使用__func__,那么你得到constexpr函数的名称;你没有得到任何调用函数的名称,这是扩展预处理器宏时会得到的。

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