用于双乘法的模板元编程
template meta-programming for a double multiplication
我试图创建一个方法,给定一个整数输入,使一些计算(只是乘法和除法)返回结果作为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"
}
相关文章:
- C++ 运算符修改/元编程策略,用于不那么冗长的语法
- 我已经安装了用于c++编程的升华3,但在编写了一个简单的程序后,我遇到了以下错误
- 用于Windows编程的可视化C++库
- 是否有任何函数可用于在 c++ 编程中传输流程,以替代 while 或 do while 循环
- 用户定义的功能用于竞争编程中,以获取输入
- 用于字符串比较的动态编程
- 用于 Windows 7 中的 C 套接字编程的 IDE
- Windows API用于C++GUI编程的优势
- 用于电子邮件捕获的元编程 Python 脚本
- 数组和向量差异用于编程
- 用于多平台大型软件开发的编程语言
- C/C++ 套接字编程 - 没有可用于"ntdll!KiFastSystemCallRet()"的源
- 关于编程原理和C++练习的"尝试这个"练习,用于迭代
- 插件接口设计,用于无偏接口,允许任何编程语言使用它
- 打印用于模板元编程的静态变量
- 如何序列化一个8位整数的结构用于套接字编程
- C++中用于嵌套循环的OpenMP编程的锁定策略
- 用于优化存储/运行时算法的元编程,C++
- 用于编程练习的重载运算符
- C++编程的 DAW 用于图形渲染和音频输出