Home > Net >  How to use c 20 concepts on classes
How to use c 20 concepts on classes

Time:10-08

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

Are c 20 concepts only available for functions?

CodePudding user response:

Concepts are available for class templates. Concept-based overloading is not - you still can have only one class template of a given name, just like before.

You can use concepts for specialization though.

CodePudding user response:

Template functions support both overloading and specialization. Template classes only support specialization.

So in your f case, there are two independent overloads of f; you can have more than one template function with the same name, they overload. In the class case, there are two different template classes with the same name, which is not allowed.

On the other hand, template specialization for classes is stronger than function template specialization.

#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.

  • Related