平方根元功能?

编程入门 行业动态 更新时间:2024-10-18 10:29:25
本文介绍了平方根元功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以使用具有以下签名的元函数来计算整数的平方根:

Is it possible to compute the square root of an integer with a metafunction with the following signature :

template<unsigned int N> inline double sqrt();

(或者也许使用constexpr关键字,我不知道什么是最好的). 这样,sqrt<2>()将在编译时替换为1.414....

(or maybe using the constexpr keyword, I don't know what is the best). With that, sqrt<2>() would be replaced by 1.414... at compile-time.

这种功能的最佳实现是什么?

What would be the best implementation for a such function ?

推荐答案

这可能不是您想要的,但我想确保您意识到,通常情况下,通过优化,编译器无论如何都会在编译时计算结果.例如,如果您具有以下代码:

This may not be what you are looking for, but I wanted to make sure you realized that typically with optimization the compiler will calculate the result at compile time anyway. For example, if you have this code:

void g() { f(sqrt(42)); }

对于具有优化-O2的g ++ 4.6.3,生成的汇编代码为:

With g++ 4.6.3 with optimization -O2, the resulting assembly code is:

9 0000 83EC1C subl $28, %esp 11 0003 DD050000 fldl .LC0 12 0009 DD1C24 fstpl (%esp) 13 000c E8FCFFFF call _Z1fd 14 0011 83C41C addl $28, %esp 16 0014 C3 ret 73 .LC0: 74 0000 6412264A .long 1244009060 75 0004 47EC1940 .long 1075440711

sqrt函数从不实际调用,其值仅存储为程序的一部分.

The sqrt function is never actually called, and the value is just stored as part of the program.

因此,要创建一个技术上满足您要求的功能,您只需要:

Therefore to create a function that technically meets your requirements, you simply would need:

template<unsigned int N> inline double meta_sqrt() { return sqrt(N); }

更多推荐

平方根元功能?

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

发布评论

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

>www.elefans.com

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