【问题标题】:Rewriting a small C-define into "normal" C++ function将一个小的 C 定义重写为“普通”C++ 函数
【发布时间】:2020-01-09 11:48:15
【问题描述】:

我从<X11/Xutil.h>找到了这段代码并雕刻出来

#define XGetPixel(ximage, x, y) \
    ((*((ximage)->f.get_pixel))((ximage), (x), (y)))

我想把它改写成一个普通函数,但我不知道怎么做。有人可以帮忙吗?

澄清:

  • 当那一小段代码也在 C++ 中工作时,我想在这里实现什么?

    我想了解它是什么,以及将来如何自己重写。

  • 我用它做什么?

    单像素颜色RGB提取。

  • 我在 C++ 中编码多长时间以及在什么环境中编码?

    我在 Linux (Mint 19) g++-8 上是一个 shell 脚本编写者,而不是 C++ 编码器,总共只在 C++ 上花了大约半年时间。

  • 我为什么不干脆#include <X11/Xutil.h>

    我只是不认为我需要它,最好坚持使用 X11/Xlib.h 我相信,如果我错了,请纠正我。

【问题讨论】:

标签: c++ c function


【解决方案1】:

The documentation calls this a function;可能他们已经把它变成了一个宏来代替“性能”,并认为它是一个as-if implementation;我不会有,但没关系。

但这意味着文档会告诉您参数类型和返回类型,这是您需要知道的全部内容。

unsigned long XGetPixel(ximage, x, y)
      XImage *ximage;
      int x;
      int y;

你已经知道实现了:

((*((ximage)->f.get_pixel))((ximage), (x), (y)))

所以,并删除一些现在冗余的括号:

unsigned long XGetPixel(XImage* ximage, int x, int y)
{
    return (*ximage->f.get_pixel)(ximage, x, y);
}

请注意,这不会与宏冲突,由于宏是无范围的,因此很容易发生冲突。

【讨论】:

    【解决方案2】:

    在不知道类型的情况下,您可能会执行以下操作:

    template <typename Image, typename X typename Y>
    auto XGetPixel(Image&& ximage, X&& x, Y&& y)
    -> decltype((*(std::forward<Image>(ximage)->f.get_pixel))(std::forward<Image>(ximage),
                                                             std::forward<X>(x),
                                                             std::forward<Y>(y)))
    {
        return (*(std::forward<Image>(ximage)->f.get_pixel))(std::forward<Image>(ximage),
                                                             std::forward<X>(x),
                                                             std::forward<Y>(y));
    }
    

    【讨论】:

      【解决方案3】:

      我会让@LightnessRacesBY-SA3.0 回答inline,并添加const

      #if defined(__GNUC__) || defined(__clang__) || defined(__MINGW32__) || defined(__MINGW32__) || defined(__MINGW64__)
      #define INLINE inline __attribute__((always_inline))
      #else
      #define INLINE inline
      #endif 
      
      INLINE unsigned long XGetPixel(XImage* ximage, const int x, const int y)
      {
       ...
      }
      

      【讨论】:

      • 所以从那里删除。
      • 复制粘贴了您的定义代码,vscode 将后半部分显示为灰色,所以我应该使用inline __attribute__((always_inline))... :-|累了,但谢谢,我还没有对它进行基准测试,但我相信你为了速度做了内联,对吧?
      • 是的。我担心 VS 代码无法正确理解它,因为在编译期间会评估这些宏
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      相关资源
      最近更新 更多