old*_*987 1 c++ compile-time-constant compile-time constexpr c++17
我已经实现了一个constexpr编译时哈希函数,如果被调用,它可以正常工作(即在编译时进行评估)
constexpr auto hash = CompileTimeHash( "aha" );
Run Code Online (Sandbox Code Playgroud)
但是我需要在实际代码中使用它作为函数的参数
foo( CompileTimeHash( "aha" ) ); // foo is NOT constexpr
Run Code Online (Sandbox Code Playgroud)
由于某个特定原因,我不能使用长版本
constexpr auto hash = CompileTimeHash( "aha" );
foo( hash );
Run Code Online (Sandbox Code Playgroud)
编译器(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;
Run Code Online (Sandbox Code Playgroud)
并使用它像:
foo( want_static<CompileTimeHash( "aha" )> );
Run Code Online (Sandbox Code Playgroud)
即使没有优化它也可以工作,因为除非你使用解释器,否则在运行时执行它太复杂了,没有充分的理由.
分配给constexpr变量也应该有效.但实际上在编译时不能进行评估更容易,因此无论如何都不会进行优化.
foo( []{ constexpr auto r = CompileTimeHash( "aha" ); return r; }() );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |