用于双乘法的模板元编程

template meta-programming for a double multiplication

本文关键字:编程 用于      更新时间:2023-10-16

我试图创建一个方法,给定一个整数输入,使一些计算(只是乘法和除法)返回结果作为double。这个方法应该在编译时进行计算。

我试过不同的方法,像这样:

template <int n> struct Try
{
    static const double result = 1.0 / (double)n * Try<1>::result;
};
template <> struct Try<1>
{
    static const double  result = 1.0;
};

但仍然没有成功,我总是得到编译时错误。

编辑:我不使用C++11

功劳归@ForEveR,我刚刚修正了他回答中的一个小错误。注意没有保证在编译时实际进行计算。没有什么能保证编译时间。无耻地抄了下面的答案。

不能用const初始化类中的非整型变量,只能用constexpr初始化。因为你不能使用c++ 11,你可以试试这个

template <int n> struct Try;
template <> struct Try<1>
{
static const double  result;
};
template <> const double Try<1>::result = 1.0;
template<int n> struct Try
{
static const double result;
};
template<int n>
const double Try<n>::result = 1.0 / (double)n * Try<1>::result;

您可以使用另一个常量来帮助您计算结果

这里有一个函数示例。

#include <iostream>
template <int n> struct Try;
template<int n> struct Try
{
static const double result;
static const double _tmp;
};
template<int n>
const double Try<n>::_tmp = n*2; // another usefull operation because it's useless here
template<int n>
const double Try<n>::result = 1.0 / ((double)n * Try<n>::_tmp);

int main() {
        std::cout << Try<5>::result << std::endl;
}

你的问题不是很清楚,但在我看来,你想要一个分数的编译时评估成双浮点数。这可以通过一个非常简单的模板函数来实现。下面的工作示例在.rodata节中创建了双精度对象(使用gcc 4.8.2和clang 3.4进行了测试):

#include <iostream>
template<int N, int M> inline const double& Frac() {
  static const double result = (double)N/M;
  return result;
}
int main() {
  std::cout << Frac<3, 4>() << std::endl;     // prints "0.75"
}