【问题标题】:Template template parameters and "<<" operator (ostream)模板模板参数和“<<”运算符(ostream)
【发布时间】:2021-02-17 11:13:32
【问题描述】:

这几天我一直在尝试了解模板模板参数。我尝试在 Visual Studio 中使用 C++17 编写示例,但出现此错误:

Error   C2679   binary '<<': no operator found which takes a right-hand operand of type 'std::vector<int,std::allocator<int>>' (or there is no acceptable conversion)

对于这个例子,我尝试使用来自 STL 的通用容器来突出 C++ 中模板模板参数的概念。

#include <iostream>
#include <vector>
using namespace std;

template<typename T, template<typename> typename Tpl_Type>
ostream& operator <<(ostream& out,const Tpl_Type<T>& x) {
    for (auto& aux : x)
        out << aux << "   ";
    out << endl;
    return out;
}

template<typename T, template<typename>typename Tpl_Type>
void functioon()
{
    
    Tpl_Type<T> vect2;
    for (auto i = 0; i < 5; i++) {
        vect2.push_back(i);
    }
    std::cout << vect2 << endl;
    return;
}

int main()
{

    functioon<int, std::vector>();
    return 0;
}

我做错了什么?

【问题讨论】:

    标签: c++ templates parameters operator-overloading operators


    【解决方案1】:

    std::vector是一个带有多个模板参数的模板,所以functioonoperator&lt;&lt;要接受它作为模板模板参数,该模板模板参数本身需要接受一个可变数量的模板参数:

    template<typename T, template<typename ...> typename Tpl_Type>
                                        // ^^^
    

    如果不使其可变参数,clang 和 msvc 将不会编译代码。 gcc 编译两个版本,但我怀疑这是一个错误。

    这是demo

    【讨论】:

    • 不一定是错误,也许 gcc STL 实现的向量模板化只有一个参数,而其他的则不止这些。
    • @SergeyA 哦,这很奇怪。那会合规吗?如果我想使用自定义分配器进行实例化怎么办?
    • 公平点。 Allocator 确实是一个模板参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 2010-10-07
    相关资源
    最近更新 更多