条件类型声明

时间:2017-10-27 13:00:10

标签: c++ conditional std

我正在尝试获取条件类型的file_handle,具体取决于文件名是否以“.gz”结尾。我认为可以用std :: conditional完成,但下面的代码不能编译说明:

  

错误:命名空间'std'中的'conditional'没有命名模板类型

有没有人知道我做错了什么?

#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) 
{
    string filename(argv[1]);
    string file_ext = filename.substr(filename.length()-3, filename.length());
    typedef std::conditional<(file_ext == ".gz"), boost::iostreams::filtering_istream, ifstream>::type file_handle;
    if (file_ext == ".gz"){
        boost::iostreams::file_source myCprdFile (filename, std::ios_base::in | std::ios_base::binary);
        file_handle.push (boost::iostreams::gzip_decompressor());
        file_handle.push (myCprdFile);
    }
    else {
        file_handle.open(filename.c_str());
    }
    std::string itReadLine;

    while (std::getline (bunzip2Filter, itReadLine)) {
      std::cout << itReadLine << "\n";
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

因为我不太了解boost :: variant也没有让它工作,我这样解决了它,并且它正在工作......

#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;
int main(int argc, char* argv[])
{
    string filename(argv[1]);
    string file_ext = filename.substr(filename.length()-3, filename.length());
    bool is_gz = false;

    boost::iostreams::filtering_istream gzfile_handle;
    ifstream file_handle;

    if (file_ext == ".gz") {
        is_gz = true;
        boost::iostreams::file_source myCprdFile (filename, std::ios_base::in | std::ios_base::binary);
        gzfile_handle.push (boost::iostreams::gzip_decompressor());
        gzfile_handle.push (myCprdFile);
    }
    else {
        file_handle.open(filename.c_str());
    }
    std::string itReadLine;

    while (is_gz ? std::getline (gzfile_handle, itReadLine) : file_handle >> itReadLine) {
      std::cout << itReadLine << "\n";
    }

    return 0;
}