C++ 推断尖括号内的类型模板参数

huangapple go评论86阅读模式
英文:

C++ Inferring Template Arguments of Type Inside of Angle Brackets

问题

这行代码中的类型注解是否有简化的方法:

std::array<std::tuple<char, int>, 3> arr {{{'a', 1}, {'b', 2}, {'c', 3}}};

我认为这样写应该可以:

std::array<std::tuple> arr {{{'a', 1}, {'b', 2}, {'c', 3}}};

但实际上不行。
英文:

Is there anyway to simplify the type annotation in this line of code:

std::array&lt;std::tuple&lt;char, int&gt;, 3&gt; arr {{{&#39;a&#39;, 1}, {&#39;b&#39;, 2}, {&#39;c&#39;, 3}}};

I thought this would work:

std::array&lt;std::tuple&gt; arr {{{&#39;a&#39;, 1}, {&#39;b&#39;, 2}, {&#39;c&#39;, 3}}};

But it does not.

答案1

得分: 2

A placeholder for a deduced class type, i.e. the name of a class template without a template argument list like std::tuple, cannot be used as a template argument.

CTAD (class template argument deduction) is only possible if the whole specified type is a placeholder for a deduced class type, e.g.

std::array{/*...*/}

where std::array is the placeholder naming a class template without template argument list. The template argument list must not be present at all. Even std::array<int>{0, 1, 2, 3} isn't possible.

The syntax you want isn't possible. You need to make some concessions like using std::make_tuple around each element of the array initializer.

英文:

A placeholder for a deduced class type, i.e. the name of a class template without a template argument list like std::tuple, cannot be used as a template argument.

CTAD (class template argument deduction) is only possible if the whole specified type is a placeholder for a deduced class type, e.g.

std::array{/*...*/}

where std::array is the placeholder naming a class template without template argument list. The template argument list must not be present at all. Even std::array&lt;int&gt;{0, 1, 2, 3} isn't possible.

The syntax you want isn't possible. You need to make some concessions like using std::make_tuple around each element of the array initializer.

答案2

得分: 2

你可以使用 std::to_array 来简化为

auto arr = std::to_array({std::tuple{&#39;a&#39;, 1}, {&#39;b&#39;, 2}, {&#39;c&#39;, 3}});
英文:

You can use std::to_array to simplify to

auto arr = std::to_array({std::tuple{&#39;a&#39;, 1}, {&#39;b&#39;, 2}, {&#39;c&#39;, 3}});

huangapple
  • 本文由 发表于 2023年6月26日 13:44:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定