constexpr 不 work/apply 内部函数调用

constexpr does not work/apply inside function call

我已经实现了一个 constexpr 编译时散列函数,如果调用为

,它工作正常(即在编译时评估)
constexpr auto hash = CompileTimeHash( "aha" );

但我需要在实际代码中使用它作为函数的参数,如

foo( CompileTimeHash( "aha" ) ); // foo is NOT constexpr

由于特殊原因,我无法使用长版

constexpr auto hash = CompileTimeHash( "aha" );
foo( hash );

编译器 (VC++) 不会在短(第一种)情况下进行编译时散列。 有什么办法可以实现吗?

编辑:现在可以在此处找到涵盖这 3 种情况的示例: https://godbolt.org/z/JGAyuE 只有 gcc 在所有 3 种情况下都完成了它

好吧,as-if-rule 总是允许在运行时进行评估。无论这样做多么疯狂(而且极其复杂)。

强制编译器在编译时执行此操作的最佳方法是通过模板参数传递它:

一些设置:

template <auto x>
using make_integral_constant = std::integral_constant<decltype(x), x>;

template <auto x>
inline constexpr auto want_static = make_integral_constant<x>::value;

并像这样使用它:

foo( want_static<CompileTimeHash( "aha" )> );

works even without optimization,因为除非你使用解释器,否则在运行时执行它太复杂了,没有充分的理由。


分配给 constexpr 变量也应该有效。但实际上在编译时不求值更容易,所以 without optimization that happens anyway.

foo( []{ constexpr auto r = CompileTimeHash( "aha" ); return r; }() );

更新:在 C++ 20 中,一个新的关键字 consteval 可用于定义立即数函数,该函数将 始终 在编译时计算。 constinit 可用于强制使用 constexpr 规则进行初始化,而无需使其成为 constexpr.

consteval auto immediate(auto x) { return x; }

如果我没理解错的话,你的CompileTimeHash()return一个int.

那么

foo( sizeof(char[CompileTimeHash( "aha" )]) );

?

如果CompileTimeHash() return只有正数,显然。

如果CompileTimeHash() return 非负数(正数或零),你可以解决零问题(对于C风格数组来说不可接受的大小)加(内)和减(外面) 1

我是说

foo( sizeof(char[CompileTimeHash( "aha" )+1])-1u );