用可变参数模板初始化向量

时间:2021-06-02 02:16:02

标签: c++ templates vector variadic-templates parameter-pack

基本上我需要模板函数,它将容器的大小与一些常量进行比较。所以我需要制作容器的 std::vector 并检查谓词 compSize 是否为真。

template < int x, class Container >
bool compSize(Container cont)
{
    return x == cont.size();
}
    
template < int x, class ...Container >
bool compSizeMult(Container ...conts)
{
    std::vector< Container > cvector{ conts... };
    return std::all_of(cvector.cbegin(), cvector.cend(), compSize< x, Container >);
}

但是编译器说,那个参数包没有扩展

<块引用>

cvector{ conts... };

此外,我想使用 compSizeMult 作为 std::sort 的比较器并制作类似

int main()
{
    std::vector< std::vector< int > > vec{{1}, {2}, {3}, {0}, {0}};
    std::sort(vec.begin(), vec.end(), compSizeMult< 0, std::vector< int > >);
}

这就是函数应该接受多个参数的原因。我不能在这个任务中使用循环和 lambdas,只能使用标准算法

1 个答案:

答案 0 :(得分:0)

你有 2 个可变参数

std::vector<Container> cvector{ conts... };
  • 变量 conts 有它的 ...
  • 输入没有 Container...(不在 compSize<x, Container> 中)。

您可能需要std::common_type_t<Container...>

在 C++17 中,您可能会使用 Fold expressions

template < int x, class ... Containers >
bool compSizeMult(Containers&&... conts)
{
    return (compSize<x>(conts) && ...);
    // or directly: return (conts.size == x && ...);
}
<块引用>

我想使用 compSizeMult 作为比较器

它不是一个有效的比较器。它打破了 strict weak ordering