如 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; }
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; }