【问题标题】:Initializing vector with variadic template使用可变参数模板初始化向量
【发布时间】:2021-08-20 04:41:49
【问题描述】:

基本上我需要模板函数,它将容器的大小与某个常数进行比较。所以我需要制作容器的 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{ 继续... };

我也想使用 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 > >);
}

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

【问题讨论】:

  • 标准规定允许在初始化列表中使用可变参数模板。其他答案包含代码 sn-ps,其中以这种方式使用可变参数模板。但是......它只是不起作用
  • 我刚刚意识到我不能使用这个函数作为比较器

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


【解决方案1】:

你有 2 个可变参数

std::vector<Container> cvector{ conts... };
  • 变量conts有其...
  • 键入没有...ContainercompSize&lt;x, Container&gt; 中也没有)。

你可能想要std::common_type_t&lt;Container...&gt;

在 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

【讨论】:

  • 所以我不能将 conts 解压成向量?
  • std::vector&lt;std::common_type_t&lt;Container...&gt;&gt; cvector{ conts... }; 应该可以工作(如果有通用类型,则不能将 std::vector&lt;int&gt;std::list&lt;int&gt; 与 std::vector). Alternatively, you can std::vector<: size_t> 大小{conts.size()...};`
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 2016-07-14
  • 2017-05-15
  • 2018-04-27
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
相关资源
最近更新 更多