平方根元功能? [英] Square root metafunction?

查看:123
本文介绍了平方根元功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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); }

这篇关于平方根元功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆