3

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?

Ethanabc
  • 311
  • 2
  • 7
  • 1
    not sure what the question is, but what you did is same what std concepts do, see for example: https://en.cppreference.com/w/cpp/concepts/floating_point (except they use _v instead of ::value to save typing) – NoSenseEtAl Apr 08 '21 at 22:00
  • 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 https://coliru.stacked-crooked.com/a/659565761faf0dac – Catriel Feb 02 '23 at 20:48

1 Answers1

0

This worked for me:

template <typename T>
concept NumericType= std::integral<T> || std::floating_point<T>;
Hossein
  • 1
  • 2
  • 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](/help/how-to-answer). – Community Jun 25 '23 at 09:00