【问题标题】:Is there a workaround for template template arguments being invisible?是否有模板模板参数不可见的解决方法?
【发布时间】:2021-02-11 13:40:03
【问题描述】:

考虑以下代码:

template<typename... Args1> 
constexpr size_t direct = sizeof... (Args1);

template<template<typename... Args1> typename A1> 
constexpr size_t nested = sizeof... (Args1); // compile error ☹️

嵌套行无法编译,因为(我认为)Args1 是嵌套参数。

有没有办法以非侵入性的方式解决这个问题?侵入性是指修改传递的类型,例如添加

constexpr size_t sizeof_args = sizeof... (Args...);

传递给这个模板的每个模板。

注意:我很擅长使用 C++20 概念,但 AFAIK 他们并没有在这个领域提供改进。

【问题讨论】:

  • 您要使用nested&lt;std::vector&gt; 还是nested&lt;std::vector&lt;int&gt;&gt;
  • @Jarod42 不确定问题是什么,我最初想要的(在我将代码简化为问题中的代码之前)是比较第二个模板参数,例如 std::array和 std::array 应该返回相同, std::map std::unordered_map 应该返回相同 ...
  • std::array 很特别,因为它混合了类型和非类型模板参数。但模板也可以有“模板模板参数”,因为std::vector 不是类型,但std::vector&lt;int&gt; 是。我们可能会为这两种情况编写特征。 std::vector 有 2 种类型参数(T 和(默认)Allocator),std::vector&lt;int/*, std::allocator&lt;int&gt;*/&gt; 也有 2 种类型。 std::tuple 没有固定数量的参数,std::tuple&lt;int&gt; 有一个,std::tuple&lt;int, char&gt; 有两个。

标签: c++ c++20 template-templates


【解决方案1】:

您可以编写一个主变量模板,然后将变量模板特化为模板模板参数。

这允许您单独显式命名模板模板参数的模板参数:

template<typename ...> 
constexpr size_t nested = -1; // any value will do, 
                              // but prefer one that is invalid for specializations

template<template<typename ...> typename A1, typename... Args1> 
                // name the parameters here  ^_______________^
constexpr size_t nested<A1<Args1...>> = sizeof...(Args1);
    // specialize here ^____________^

C++20 中添加的概念功能在这里没有任何帮助,因为没有任何限制。

这是demo

【讨论】:

  • 是的,应该是size_t/int,我是在减少我原来的代码,搞砸了
  • 轻度题外话,但您知道为什么会存在原始问题吗?我的意思是您的代码是很酷的解决方案,但对于相对常见的问题似乎很难解决,我天真地希望通过使嵌套模板参数可见来解决。
  • @NoSenseEtAl 只是从来没有这样指定过。我不确定是否有任何 基本 原因不允许命名这些参数。我认为有一个关于 why 之前在 SO 上被问过的问题;我看看能不能找到。
  • @NoSenseEtAl:让它们“可见”是没有意义的:在问题的版本中,你可以写nested&lt;std::tuple&gt;,值应该是多少?
猜你喜欢
  • 2022-01-16
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 2019-02-22
相关资源
最近更新 更多