我已经实现了 constexpr 编译时的哈希函数,如果调用为
$ b $,则可以很好地工作(即在编译时进行评估)。 b
constexpr自动哈希= CompileTimeHash( aha);但是我需要在实际代码中使用它作为函数的自变量,如
foo(CompileTimeHash( aha)); // foo不是constexpr由于特定原因,我不能使用长版本
constexpr自动哈希= CompileTimeHash( aha); foo(hash);在简短的(第一种)情况下,编译器(VC ++)不会编译时哈希。 有什么方法可以实现?
编辑:现在可以找到涉及3种情况的示例: godbolt/z/JGAyuE 只有gcc才能完成所有这三种情况
解决方案按规则,总是允许在运行时进行评估。
最好的方法是强制编译器在编译时执行此操作,并通过模板参数传递它: / p>
一些设置:
template< auto x> 使用make_integral_constant = std :: integral_constant< decltype(x),x> ;; 模板< auto x> 内联constexpr auto want_static = make_integral_constant< x> :: value;并像这样使用它:
foo(want_static< CompileTimeHash( aha)>);它即使在没有优化的情况下也可以工作,因为除非您使用解释器,否则在运行时执行它就太复杂了,无缘无故。
分配给 constexpr 变量也应该可行。但是实际上,在编译时不进行评估实际上更容易,因此无需进行任何优化。。 p>
foo([] {constexpr auto r = CompileTimeHash( aha); return r;}());
I have implemented a constexpr compile-time hash-function, which works fine (i.e. is evaluated at compile-time) if called as
constexpr auto hash = CompileTimeHash( "aha" );but I need to use it in actual code as an argument to a function as in
foo( CompileTimeHash( "aha" ) ); // foo is NOT constexprFor a specific reason, I cannot use the long version
constexpr auto hash = CompileTimeHash( "aha" ); foo( hash );The compiler (VC++) will not compile-time hash in the short (first) case. Is there any way to achieve this?
EDIT: An example covering the 3 cases is now found here: godbolt/z/JGAyuE Only gcc gets it done in all 3 cases
解决方案Well, the as-if-rule always allows evaluation at runtime. However insane (and insanely complex) doing so might be.
Best shot to force your compiler to do it at compile-time, pass it through a template-argument:
A bit of setup:
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;And use it like:
foo( want_static<CompileTimeHash( "aha" )> );It works even without optimization, because unless you use an interpreter, doing it at runtime instead is too complex to do for no good reason.
Assigning to a constexpr-variable should also work. But it is actually easier to not evaluate at compile-time, so without optimization that happens anyway.
foo( []{ constexpr auto r = CompileTimeHash( "aha" ); return r; }() );
更多推荐
constexpr在函数调用中不起作用/应用
发布评论