【问题标题】:Why does variadic template not work in template introduction but work in requires-clause? ConceptName{T,U,V,W} <-- template<typename ...T>为什么可变参数模板在模板介绍中不起作用,但在要求子句中起作用? ConceptName{T,U,V,W} <-- 模板<类型名 ...T>
【发布时间】:2018-01-19 12:29:52
【问题描述】:

我们有:

template <typename ...T> concept bool Numerics = ( std::is_arithmetic_v<T> && ... ) ;
template <typename T>    concept bool Numeric  =   std::is_arithmetic_v<T>;

所以我们可以使用如下的 requires 子句来应用类型约束:

template <typename T, typename U, typename V, typename W> requires Numerics<T,U,V,W>
auto foo(T arg1, U arg2, V arg3, W arg4) {
    return arg1 + arg2 + arg3 + arg4;
}

但是我们不能这样写模板介绍格式:

// err: no match concept
// 
// Numerics{T,U,V,W}
// auto foo2(T arg1, U arg2, V arg3, W arg4) {
//     return arg1 + arg2 + arg3 + arg4;
// }

必须明确定义固定数量的参数:

template <typename T, typename U, typename V, typename W>
                         concept bool Numeric4 =   Numerics<T,U,V,W>;

Numeric4{T,U,V,W}
auto foo3(T arg1, U arg2, V arg3, W arg4) {
    return arg1 + arg2 + arg3 + arg4;
}

为什么template &lt;typename ...T&gt; concept 不能在模板介绍格式中工作,而在 requires 子句中工作?

LIVE

【问题讨论】:

标签: c++ templates variadic-templates c++-concepts


【解决方案1】:

首先,请注意,此语法已从概念 TS 的latest draft 中删除。


previous draft 中,此语法在 [temp.intro] 中定义并且定义明确:

Numerics{T,U,V,W}
auto foo2(T arg1, U arg2, V arg3, W arg4) {
    return arg1 + arg2 + arg3 + arg4;
}

应该针对每个introduced-parameter,根据其模式调整Numerics 中的参数包,并根据该模式声明一个模板参数。所以这应该相当于:

template <typename T, typename U, typename V, typename W> // per [temp.intro]/2
     requires Numerics<T,U,V,W> // per [temp.intro]/5
auto foo2(T arg1, U arg2, V arg3, W arg4) {
    return arg1 + arg2 + arg3 + arg4;
}

本节中有更多示例说明这应该有效。根据这个草案,代码格式正确。


也就是说,如前所述,该语法已从 TS 中删除,并且不会出现在 C++20 工作草案中。将来可能会或可能不会以这种形式或其他方式添加它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    相关资源
    最近更新 更多