【问题标题】:Can you use class template argument deduction when the class is template parameter of another template?当类是另一个模板的模板参数时,您可以使用类模板参数推导吗?
【发布时间】:2018-10-25 12:47:14
【问题描述】:

我试着写这样的代码:

#include <string>
#include <vector>
#include <utility>

using namespace std::string_literals;
int main(){
    std::vector v{1,2,3};
    std::pair p{1,"a"s};
    //std::vector<std::pair> vp{{1,"a"s}, {2, "b"s},{3,"c"s}};  // ERROR
}

但是它在pair是vector的模板参数的那一行给出了编译错误。

有没有办法让类模板推导在这里工作,还是我需要为配对指定模板参数?

【问题讨论】:

  • @PiotrNycz tnx,已修复

标签: c++ templates c++17


【解决方案1】:

目前不支持此功能。来自[dcl.type.class.deduct]p2

推导的类类型的占位符也可以[在变量声明中也作为类型]在 new-type-idtype-specifier-seq 中使用或 new-expressiontype-id,或作为显式类型转换(功能符号)中的 simple-type-specifier推导的类类型的占位符不得出现在任何其他上下文中。

从我突出显示的那句话中可以看出,由于你的使用与上面提到的任何地方都不匹配,所以你的代码格式不正确。

你可以这样做:

std::vector vp{std::pair{1, "a"s}, {2, "b"s}, {3, "c"s}};

【讨论】:

  • 我不理解标准报价,但我假设您理解,并且它确实说明了您所说的接受。 :)
  • @NoSenseEtAl 我要“翻译”它:“没有模板参数列表的模板名称也可以在 new 表达式中使用(作为类型),或者作为类型显式类型转换(函数式表示法)。这样的模板名称不能出现在任何其他上下文中。"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多