【问题标题】:C++ alias for sin to std::sin - need sloppy quick-fixsin 到 std::sin 的 C++ 别名 - 需要草率的快速修复
【发布时间】:2013-10-18 21:51:52
【问题描述】:

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

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

但我没有运气

有什么建议吗? 谢谢

【问题讨论】:

  • #define std 可怕我知道。
  • @john,std 命名空间存在,但 c++11 版本的 sin 和 cos 不在其中。它们只有旧版本,位于命名空间之外。
  • std::sinstd::cos 不是来自 C++11,它们从那时起就是 C++ 的一部分。只需包含<cmath> 而不是<math.h>。如果该评论是垃圾,那么请让问题更具体一点,这个“过时的编译器”实际上缺少什么。

标签: c++ function c++11 namespaces alias


【解决方案1】:

原则上应该可以使用

#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 是否被定义:您需要设置一个合适的宏名称。

【讨论】:

  • thx,我选择了后者,只是为 sin 和 cos 做了花车 :)
  • 在 std 命名空间中已经有这些函数的编译器不会出现多重定义错误吗?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您不应污染 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 或(因为std::sin(double) 不存在)中调用sin,全局命名空间。您可能需要浮动等重载。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 2015-08-12
      相关资源
      最近更新 更多