[英]How to use a concept for STL containers?
基於這個舊的堆棧溢出問題,您如何為標准庫容器定義 C++ 概念?
我看到可以為 STL 容器定義一個概念。 但是,我不確定如何將這個概念實際應用於任何事物,因為它需要 2 個容器,即容器 a 和容器 b。
例如,獲取最受贊譽的答案的簽名
template <class ContainerType>
concept Container = requires(ContainerType a, const ContainerType b)
我只看到僅與 1 個需求參數一起使用的概念,就像這樣
//source: https://en.cppreference.com/w/cpp/language/constraints
template<typename T>
concept Hashable = requires(T a)
{
{ std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;
};
struct meow {};
// 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> {}
int main()
{
using std::operator""s;
f("abc"s); // OK, std::string satisfies Hashable
// f(meow{}); // Error: meow does not satisfy Hashable
}
這個概念的定義其實是
template <class ContainerType>
concept Container = /* */;
它只約束一種類型ContainerType
,因此應用此概念的 function 將是
template <Container C>
void f(C& c);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.