c++ - 根据三元表达式声明变量类型

标签 c++ qt qt5 variable-declaration

我必须根据用户的选择以 XMLCSV 格式从数据库中导出数据。
我有这样的选择:

const bool isXml = (cbxFormat->currentIndex() == 1 ? true : false);

为了编写导出文件,我使用了 QXmlStreamWriterQTextStream
我想避免使用 if/else 语句来声明我的流。
我尝试像这样使用 decltype:

decltype( (isXml ? QXmlStreamWriter() : QTextStream()) ) stream;

但我不能,因为 QXmlStreamWriterQTextStream 没有相同的基类,在基类相同的情况下, 的类型stream 是“最宽”的类型。

我也尝试过使用 std::conditional 但我不能,因为 isXml 在运行时是已知的:

std::conditional<isXml, QXmlStreamWriter, QTextStream>::type stream;

是否存在可行的解决方案?

QFile expFile(fileName);
if (expFile.open(QIODevice::WriteOnly)) {
    /* not possible */
    // decltype( (isXml ? QXmlStreamWriter() : QTextStream()) ) stream;
    /* isXml is known at runtime */
    // std::conditional<isXml, QXmlStreamWriter, QTextStream>::type stream(&expFile);
    // If not possible... if/else

    // filling my stream..

    expFile.close();
}

最佳答案

您可以编写一个将类型作为模板参数的函数,并使用 if 调用具有适当类型的函数:

template <typename StreamT>
void do_work(QFile& file) {
    StreamT stream;
    // ...
    stream << strData;
}

void work() {
  QFile file(file_name);
  // ...
  if (isXml) {
    do_work<QXmlStreamWriter>(file);
  } else {
    do_work<QTextStream>(file);
  }
}

编辑:

另一种解决方案是将流包装在类中:

struct stream_base {
  virtual void work(QFile&) = 0;
};
struct xml_stream: stream_base {
  virtual void work(QFile&) { QXmlStreamWriter stream; ... }
};
struct text_stream: stream_base {
  virtual void work(QFile&) { QTextStream stream; ... }
};
std::unique_ptr<stream_base> make_stream(bool isXml) {
  return isXml ? std::make_unique<xml_stream>() : std::make_unique<text_stream> ();
}

void work () {
  QFile file (file_name);
  // ...
  auto stream = make_stream(isXml);
  stream->work(file);
}

关于c++ - 根据三元表达式声明变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43919073/

相关文章:

c++ - Boost.flyweight 和 Boost.MPL

c++ - Qt 不是异常安全的。这对 C++ 代码有何影响?

qt - 如何操作Webkit窗口内的页面内容(使用QT和QTWebKit)?

c++ - 用于 Qt5 的 GDB pretty-print

c++ - IO 完成端口初始读取和双向数据

c++ - libcurl 输出到变量而不是文本文件

c++ - 如何使 QGraphicsTextItem 单行?

c++ - C2061 : syntax error : identifier 'L' in qtypetraits.小时

c++ - Qt5 QFile::close() 写入速度非常慢

c++ - 在 C++ main() 执行之前处理 Mac OS X 文件打开事件