简体   繁体   English

如何在类中使用 C++20 概念

[英]How to use c++20 concepts on classes

I'm wondering why I can use我想知道为什么我可以使用

#include <concepts>
template<std::floating_point T> 
void f();
template<std::integral T> 
void f();

but not:但不是:

#include <concepts>
template<std::floating_point T> 
struct Point
{};

template<std::integral T> 
struct Point
{};

error: declaration of template parameter 'class T' with different constraints错误:具有不同约束的模板参数“class T”的声明

Are c++20 concepts only available for functions? c++20 概念是否仅适用于函数?

Concepts are available for class templates.概念可用于 class 模板。 Concept-based overloading is not - you still can have only one class template of a given name, just like before.基于概念的重载不是——你仍然只能有一个给定名称的 class 模板,就像以前一样。

You can use concepts for specialization though.不过,您可以使用概念进行专业化。

Template functions support both overloading and specialization.模板函数支持重载和特化。 Template classes only support specialization.模板类只支持专门化。

So in your f case, there are two independent overloads of f ;因此,在您的f情况下, f有两个独立的重载; you can have more than one template function with the same name, they overload.您可以拥有多个同名模板 function,它们会超载。 In the class case, there are two different template classes with the same name, which is not allowed. class案例中,有两个不同的模板类同名,这是不允许的。

On the other hand, template specialization for classes is stronger than function template specialization.另一方面,类的模板特化强于 function 模板特化。

#include <concepts>
template<class>
struct Point;
template<std::floating_point T> 
struct Point<T>
{};

template<std::integral T> 
struct Point<T>
{};

so the above does what you probably want.所以上面做了你可能想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM