Q_ENUM 到 ostream
Q_ENUM to ostream
项目中有自定义记录器,我想扩展它以像 qDebug() 那样写入枚举值。有什么简单的方法吗?
以下是我认为可能有效(但实际上无效)的方法:
template <typename T>
typename QtPrivate::QEnableIf<QtPrivate::IsQEnumHelper<T>::Value, std::ostream>::Type
operator<<(std::ostream& os, T enumValue)
{
const QMetaObject* mo = qt_getEnumMetaObject(enumValue);
int enumIdx = mo->indexOfEnumerator(qt_getEnumName(enumValue));
return os << mo->enumerator(enumIdx).valueToKey(enumValue);
}
class MyObjet : public QObject
{
Q_OBJECT
public:
enum class Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };
Q_ENUM(Action)
explicit MyObjet(QObject* parent);
void myFunction(Action a)
{
std::count << "Action is:" << a << std::endl;
}
};
这是插入运算符重载,我把它放在一个头文件中,名为qtenum2ostream.h:
#ifndef QTENUM2OSTREAM_H
#define QTENUM2OSTREAM_H
#include <QMetaEnum>
template<typename T>
typename std::enable_if<QtPrivate::IsQEnumHelper<T>::Value, std::ostream &>::type
operator<<(std::ostream & o, const T & t)
{
const QMetaObject* metaobject = qt_getEnumMetaObject(t);
int enumindex = metaobject->indexOfEnumerator(qt_getEnumName(t));
o << metaobject->enumerator(enumindex).valueToKey(static_cast<int>(t));
return o;
}
#endif // QTENUM2OSTREAM_H
您现在可以在示例中使用它 class:
#include "qtenum2ostream.h"
#include <iostream>
#include <QObject>
class MyObject : public QObject {
Q_OBJECT
public:
enum class Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };
Q_ENUM(Action)
void myFunction(Action a)
{
std::cout << "Action is:" << a << std::endl;
}
};
项目中有自定义记录器,我想扩展它以像 qDebug() 那样写入枚举值。有什么简单的方法吗?
以下是我认为可能有效(但实际上无效)的方法:
template <typename T>
typename QtPrivate::QEnableIf<QtPrivate::IsQEnumHelper<T>::Value, std::ostream>::Type
operator<<(std::ostream& os, T enumValue)
{
const QMetaObject* mo = qt_getEnumMetaObject(enumValue);
int enumIdx = mo->indexOfEnumerator(qt_getEnumName(enumValue));
return os << mo->enumerator(enumIdx).valueToKey(enumValue);
}
class MyObjet : public QObject
{
Q_OBJECT
public:
enum class Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };
Q_ENUM(Action)
explicit MyObjet(QObject* parent);
void myFunction(Action a)
{
std::count << "Action is:" << a << std::endl;
}
};
这是插入运算符重载,我把它放在一个头文件中,名为qtenum2ostream.h:
#ifndef QTENUM2OSTREAM_H
#define QTENUM2OSTREAM_H
#include <QMetaEnum>
template<typename T>
typename std::enable_if<QtPrivate::IsQEnumHelper<T>::Value, std::ostream &>::type
operator<<(std::ostream & o, const T & t)
{
const QMetaObject* metaobject = qt_getEnumMetaObject(t);
int enumindex = metaobject->indexOfEnumerator(qt_getEnumName(t));
o << metaobject->enumerator(enumindex).valueToKey(static_cast<int>(t));
return o;
}
#endif // QTENUM2OSTREAM_H
您现在可以在示例中使用它 class:
#include "qtenum2ostream.h"
#include <iostream>
#include <QObject>
class MyObject : public QObject {
Q_OBJECT
public:
enum class Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };
Q_ENUM(Action)
void myFunction(Action a)
{
std::cout << "Action is:" << a << std::endl;
}
};