Steffen Roeber
Steffen Roeber

Reputation: 153

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

Are c++20 concepts only available for functions?

Upvotes: 0

Views: 313

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

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.

Upvotes: 2

Sebastian Redl
Sebastian Redl

Reputation: 71959

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.

Upvotes: 2

Related Questions