c++ - 如何避免多平台qt代码中的特定#ifdef?
问题描述
我有一个 QT 输入侦听器类,它stdin
在运行中发出输入信号QCoreApplication
。我想在 Windows 和 linux 上都使用它。
我目前的方法是#ifdef Q_OS_WIN
在 header 和 cpp 中使用来执行特定于平台的代码。据我所知,这#ifdef
被认为是有害的,应该避免,我想以一种方式重构它,我只有一个头文件inputlistener.h
,让构建系统在特定的windows/inputlistener.cpp
or之间进行选择linux/inputlistener.cpp
,也许还有一个inputlistener_global.cpp
包含代码的附加文件,即不特定于平台。
但是,我找不到解决方案,如何让#ifdef
标题中的内容不碍事。
我怎样才能做到这一点?
这是我目前的方法:
#inputlistener.h
#ifndef INPUTLISTENER_H
#define INPUTLISTENER_H
#include <QtCore>
class inputlistener : public QObject {
Q_OBJECT
private:
#ifdef Q_OS_WIN
QWinEventNotifier* m_notifier;
#else
QSocketNotifier* m_notifier;
#endif
signals:
void inputeventhappened(int keycode);
private slots:
void readyRead();
public:
inputlistener();
};
#endif // INPUTLISTENER_H
#inputlistener.cpp
#include "inputlistener.h"
#include "curses.h"
#ifdef Q_OS_WIN
#include <windows.h>
#endif
inputlistener::inputlistener()
{
#ifdef Q_OS_WIN
m_notifier = new QWinEventNotifier(GetStdHandle(STD_INPUT_HANDLE));
connect(m_notifier, &QWinEventNotifier::activated
#else
m_notifier = new QSocketNotifier(0, QSocketNotifier::Read, this);
connect(m_notifier, &QSocketNotifier::activated
#endif
,
this, &inputlistener::readyRead);
readyRead(); // data might be already available without notification
}
void inputlistener::readyRead()
{
// It's OK to call this with no data available to be read.
int c;
while ((c = getch()) != ERR) {
emit inputeventhappened(c);
}
}
解决方案
您可以为和创建单独EventListener.cpp
的文件并将这些文件放入 ( , ) 等子目录中。您可以在 makefile 或 projectfile 中添加一个基于当前平台的实现文件。编译器只会为当前平台编译一个文件。windows
unix
win
linux
使用这种方法,您可以完全避免ifdef
ing。
如果定义不同,您可以使用pImpl
idiom 来分隔类的实现细节:https ://cpppatterns.com/patterns/pimpl.html
推荐阅读
- go - 如何使用 *time.Time 在协议缓冲区的结构中声明
- c# - StackExchange.Redis - 如何获取密钥的类型?
- javascript - className 如何将错误的东西返回给我?
- python - 如何使用 python 查找图像文件并以不同的文件格式保存它们?
- macos - 检测何时按下音量按钮
- r - 使用 merge 或 left_join 合并数据帧时如何将向量保持为“已标记”?
- r - dplyr 中是否有“unfilter”来将更改与原始数据集合并?
- android - Android Brother SDK 标签打印编码 - 变音符号
- python - NLP Python 逐字查找前 5 个主题 - 调查
- javascript - 离子4语音识别