📜  c++ require 关键字 - C++ 代码示例

📅  最后修改于: 2022-03-11 14:44:45.452000             🧑  作者: Mango

代码示例1
#include 
#include 
#include 
 
// Declaration of the concept "Hashable", which is satisfied by any type 'T'
// such that for values 'a' of type 'T', the expression std::hash{}(a)
// compiles and its result is convertible to std::size_t
template
concept Hashable = requires(T a) {
    { std::hash{}(a) } -> std::convertible_to;
};
 
struct meow {};
 
// Constrained C++20 function template:
template
void f(T) {}
//
// Alternative ways to apply the same constraint:
// template
//    requires Hashable
// void f(T) {}
//
// template
// void f(T) requires Hashable {}
 
int main() {
  using std::operator""s;
  f("abc"s); // OK, std::string satisfies Hashable
//f(meow{}); // Error: meow does not satisfy Hashable
}