How to use concept to restrict typename to numeric? C++20 features
Asked Answered
T

2

7

I am learning some modern C++20 features. One of them is concept. I have read https://en.cppreference.com/w/cpp/language/constraints and https://www.modernescpp.com/index.php/defintion-of-concepts to get some examples to follow.

For now, I want to design a concept such that I can only accept numeric data type. In the traditional method, one can use

template<typename NumericType,
        typename = typename std::enable_if<std::is_arithmetic<NumericType>::value,NumericType>::type>

as suggested in Class template for numeric types

or one may also use static_assert() inside the definition of template class/function

static_assert(std::is_arithmetic<NumericType>::value, "NumericType must be numeric");

I am wondering what the syntax for concept should be? For now, I am doing

template<typename NumericType>
concept Numeric = std::is_arithmetic<NumericType>::value ;

and find that

template<Numeric T>
void f(T){}

can do the trick I expected (basically just duck typing). I am wondering am I correct or is there any difference?

Tufthunter answered 8/4, 2021 at 19:8 Comment(2)
not sure what the question is, but what you did is same what std concepts do, see for example: en.cppreference.com/w/cpp/concepts/floating_point (except they use _v instead of ::value to save typing)Counterstroke
std::floating_point doesn't quite do the trick. If you have integers mixed with floating point types, you may have issues. For example, check coliru.stacked-crooked.com/a/659565761faf0dacOna
C
3

I am wondering am I correct or is there any difference?

You're correct.

Using SFINAE / std::enable_if to constrain templates has the same essential effect of concept-constrained templates.

SFINAE has additional (negative) side-effects (see WG21 P0225R0 Why I want Concepts, and why I want them sooner rather than later).

SFINAE is less a technology and more hack of C++. From this point of view the most important thing concepts can do is to be human readable!

Also take a look at: Do C++20 Concepts replace other forms of constraints? for a borderline case.

I am wondering what the syntax for concept should be?

Your syntax is right. Perhaps

template<class T> concept Numeric = std::is_arithmetic_v<T>;

is a bit shorter.

Chapfallen answered 16/12, 2023 at 17:44 Comment(0)
M
2

This worked for me:

template <typename T>
concept NumericType= std::integral<T> || std::floating_point<T>;
Montage answered 22/6, 2023 at 13:47 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Surveying

© 2022 - 2024 — McMap. All rights reserved.