constexpr在函数调用中不起作用/应用

编程入门 行业动态 更新时间:2024-10-25 02:25:26
本文介绍了constexpr在函数调用中不起作用/应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经实现了 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 constexpr

For 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在函数调用中不起作用/应用

本文发布于:2023-11-27 21:18:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639638.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   函数   constexpr

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!