C++ sin 的别名到 std::sin - 需要草率的快速修复

C++ alias for sin to std::sin - need sloppy quick-fix

本文关键字:sin 草率 别名 std C++      更新时间:2023-10-16

我有一个客户端试图在一个过时的编译器上编译,该编译器似乎没有 c++11 的 std::sin 和 std::cos。(他们无法升级(我正在寻找某种快速修复方法,以打入标题的顶部以使 std::sin 指向罪恶等。我一直在尝试这样的事情

#ifndef std::sin
something something
namespace std{
point sin to outside sin
point cos to outside cos
};
#endif

但我没有任何运气

有什么提示吗?谢谢

原则上,它应该可以使用

#include <math.h>
namespace std {
    using ::sin;
    using ::cos;
}

但是,其中一些函数是以有趣的方式实现的,您可能需要改用这样的东西:

#include <math.h>
namespace std {
    inline float       sin(float f)        { return ::sinf(f); }
    inline double      sin(double d)       { return ::sin(d); }
    inline long double sin(long double ld) { return ::sinl(ld); }
    inline float       cos(float f)        { return ::cosf(f); }
    inline double      cos(double d)       { return ::cos(d); }
    inline long double cos(long double ld) { return ::cosl(ld); }
}

请注意,这两种方法都不是可移植的,它们可能有效,也可能无效。另外,请注意,您无法测试正在定义的std::sin:您需要设置一个合适的宏名称。

一种选择是像这样使用对函数的引用......

#include <math.h>
namespace std
{
    typedef double (&sinfunc)(double);
    static const sinfunc sin = ::sin;
}

你不应该污染 std 命名空间,但以下内容可能有效:

struct MYLIB_double {
    double v_;
    MYLIB_double (double v) : v_(v) {}
};
namespace std {
   inline double sin(MYLIB_double d) {
        return sin(d.v_);
   }
}

如果命名空间 std 中存在 ' sin ',则直接使用 double 的参数调用它。 如果没有,则该值将被隐式转换为 ' MYLIB_double ',并且将调用重载,这将在std或全局命名空间中调用sin(因为std::sin(double)不存在(。 您可能需要重载来浮点等。

另一个可能更好的建议是添加一个他们可以使用的条件:

#ifdef MYLIB_NO_STD_SIN
namespace std {
   inline double sin(double x) {
        return ::sin(x);
   }
}
#endif