c++ - 当标头包含c ++时运行函数
问题描述
我正在单个头文件中构建快速三角函数逼近。
#ifndef COOL_MATH_H
#define COOL_MATH_H
#include <cmath>
const float PI = std::acos(-1);
namespace trigonometry
{
namespace
{
float _cos[180];
}
void init()
{
for (int i = 0; i < 90; i++)
{
_cos[i] = cosf(float(i) * PI/180.0f);
}
}
float cos(float deg)
{
int nearest = int(abs(deg) + 0.5) % 90;
return _cos[nearest];
}
float sin(float deg)
{
return cos(90.0f - deg);
}
}
#endif
如果我错了,请纠正我,但这个近似值理论上比内置的三角函数更快?
trigonometry::init()
主要问题是:如果包含头文件(即只有一次),我如何运行该函数?我只想存储_cos[180]
一次的值。
解决方案
当包含头文件(即仅一次)时,如何运行函数 trigonometry::init() ?
#ifndef COOL_MATH_H
#define COOL_MATH_H
#include <cmath>
#include <array>
const float PI = std::acos(-1);
namespace trigonometry
{
namespace
{
std::array<float, 180> init()
{
std::array<float, 180> cos;
for (int i = 0; i < 90; i++)
{
cos[i] = cosf(float(i) * PI/180.0f);
}
return cos;
}
std::array<float, 180> _cos = init();
}
float cos(float deg)
{
int nearest = int(abs(deg) + 0.5) % 90;
return _cos[nearest];
}
float sin(float deg)
{
return cos(90.0f - deg);
}
}
#endif
请注意,包括您的 cool_math.h 在内的每个翻译单元都有自己的数组float _cos[180]
和弱函数。要float _cos[180]
在所有翻译单元之间实现唯一共享,您需要将数组和函数定义移动到cool_math.cc,或者将它们声明为某个类的静态成员并float _cos[180]
在cool_math.cc 中定义。
推荐阅读
- puppeteer - 在 pupeeter/apify 中获取页面元素的一个属性
- node.js - 如何在 azure web 应用程序中使用 socketio 用于容器
- c++ - 将 C++ 数组写入文件,避免创建 std::string
- magento-1.9 - 如何在 Magento 1.9 的产品页面中显示简单和可配置产品的库存和缺货状态
- sorting - 定义一个自定义的 sortperm 函数
- apache-kafka - 每个主题级别的 Kafka 配置 replica.fetch.max.bytes
- reactive-programming - 结合扫描和网络请求来更新 RxSwift 中的模型
- makefile - Makefile 目标的开始和结束
- python - 将 Python 与 venv 和 PyCharm 一起使用
- javascript - 如何获得原始数据文件的链接?