首页 > 解决方案 > 当标头包含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]一次的值。

标签: c++trigonometry

解决方案


当包含头文件(即仅一次)时,如何运行函数 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 中定义。


推荐阅读