代码之家  ›  专栏  ›  技术社区  ›  Catskul

有没有什么方法可以包装boost“tee”流的构造以实现自动类型推断?

  •  0
  • Catskul  · 技术社区  · 6 年前

    C++ "hello world" Boost tee example program

    我们的目标是:

    auto myTeeStream = make_tee(std::cout, myfile);
    

    在尝试用函数make\u tee包装这个用法以允许参数的自动类型推断之后,我意识到copy和move构造函数对于必要的类型都不可用。

    所以: 在c++11中有没有一种合理的方法来包装tee流的创建

    以下是由于删除了复制构造函数和缺少移动构造函数而导致编译失败的尝试:

    #include <iostream>
    #include <ostream>
    #include <fstream>
    
    #include <boost/iostreams/tee.hpp>
    #include <boost/iostreams/stream.hpp>
    
    template <typename StreamT1, typename StreamT2>
    boost::iostreams::stream<boost::iostreams::tee_device<StreamT1, StreamT2> >
    make_tee(StreamT1 & t1, StreamT2 & t2)
    {
        using boost::iostreams::stream;
        using boost::iostreams::tee;
        return stream<decltype(tee(t1,t2))>(tee(t1,t2)); // compile error
        //return std::move(stream<decltype(tee(t1,t2))>(tee(t1,t2))); // also fails of course
    }
    
    
    int main()
    {
        {
            // desired usage
            std::ofstream myFile("file.txt");
            auto && myTee = make_tee(std::cout, myFile); // required from here
        }
        {
            // noisy default usage
            std::ofstream myFile("file.txt");
            using boost::iostreams::tee;
            using boost::iostreams::stream;
            auto && myTee = stream<decltype(tee(std::cout, myFile))>(tee(std::cout, myFile));
        }
        return 0;
    }
    

    clang++ --std=c++11 teetest.cpp 是:

    teetest.cpp:14:12: error: call to implicitly-deleted copy constructor of 'boost::iostreams::stream<boost::iostreams::tee_device<basic_ostream<char>, basic_ofstream<char> > >'
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Jarod42    6 年前

    “担保副本省略” .

    在c++11中,可以使用 return {..}

    template <typename StreamT1, typename StreamT2>
    boost::iostreams::stream<boost::iostreams::tee_device<StreamT1, StreamT2> >
    make_tee(StreamT1 & t1, StreamT2 & t2)
    {
        using boost::iostreams::stream;
        using boost::iostreams::tee;
        return {tee(t1,t2)};
    }
    

    Demo