auto 关键字与概念的使用

问题描述 投票:0回答:1

如 cppreference 所示。

auto
关键字可用于通过
concept
删除模板。

// Constrained C++20 function template:
template<Hashable T>
void f(T) {}
//
// Alternative ways to apply the same constraint:
// template<typename T>
//     requires Hashable<T>
// void f(T) {}
//
// template<typename T>
// void f(T) requires Hashable<T> {}
//
// void f(Hashable auto /* parameter-name */) {}

我的问题是当我有两个模板参数时如何使用与

auto
相同的技术。

template<typename T> requires Addable<T> // or right after a template parameter list
T add(T a, T b) { return a + b; }
c++ c++-concepts
1个回答
0
投票
template<typename T> requires Addable<T>
T add(T a, T b) { return a + b; }

这将

a
b
限制为同一类型,您能做的最好的事情就是用
typename
 替换 
Addable

template<Addable T> 
T add(T a, T b) { return a + b; }

模板参数作为概念的第一个参数传递(

T
满足
Addable<T>
),这仍然限制
a
b
为相同类型。

但是使用

auto
并不等效。

auto add(Addable auto a, Addable auto b) { return a + b; }

最后一个片段是不正确的,它不限制

a
b
为同一类型,它也不要求
a + b
格式良好,您需要为此添加一个额外的概念.

auto add(Addable auto a, Addable auto b) requires requires {a+b;} 
{ return a + b; }

神箭演示

© www.soinside.com 2019 - 2024. All rights reserved.