代码之家  ›  专栏  ›  技术社区  ›  Thomas Weller

在流缓冲区上使用variadics时,C3543“不包含参数包”

  •  0
  • Thomas Weller  · 技术社区  · 3 年前

    我想模仿Linux tee 具有多个流的命令。为了实现这一点,我实施了 streambuf 首先:

    #include <ostream>
    #include <iostream>
    #include <sstream>
    #include <vector>
    
    template<std::streambuf*... Buffers>
    class teebuf : public std::streambuf
    {
    private:
        std::vector<std::streambuf*> buffers;
        void add_all(std::streambuf* buffer, std::streambuf*... buffers)
        {
            this.buffers.push_back(buffer);
            add_all(buffers...);
        }
    public:
        teebuf(std::streambuf*... buffers)
        {
            add_all(buffers);
        }
    
        // other implementation not needed
    };
    
    int main()
    {
        std::stringstream s;
        teebuf tee(s.rdbuf(), std::cout.rdbuf());
    }
    

    但是,该类不会编译,并且错误消息为

    错误C3543:“std::basic_streambuf<char,std::char_traits>*':不包含参数包

    在第11行( add_all() )和17号线( teebuf() 构造函数)。

    我试过跟随 this suggestion 通过声明 using HelperType = typename std::streambuf*; 然后使用它,但没有区别。

    我还看到 this question 所以我声明了一个结构

    template<std::streambuf*>
    struct HelperType
    {
        using type = typename std::streambuf*;
    };
    

    并像这样使用

    void add_all(std::streambuf* buffer, typename HelperType<std::streambuf*>::type... buffers)
    [...]
    teebuf(typename HelperType<std::streambuf*>::type... buffers)
    

    但这只会导致更多的错误。

    如何编译?

    我使用的是带有C++17的VS 2022。

    1 回复  |  直到 3 年前
        1
  •  0
  •   Ted Lyngmo    3 年前

    我不确定类模板参数包将用于什么目的,所以我跳过了它。你可以通过制作 add_all 以及 teebufs 构造函数转换为函数模板:

    class teebuf : public std::streambuf {
    private:
        std::vector<std::streambuf*> buffers;
    
        template <class... Bufs>
        void add_all(std::streambuf* buffer, Bufs... bufs) {
            buffers.push_back(buffer);
            if constexpr (sizeof...(Bufs) > 0) add_all(bufs...);
        }
    
    public:
        template <class... Bufs>
        teebuf(Bufs... bufs) {
            add_all(bufs...);
        }
    };