Check Compilation Processing Time

I cannot find a compile-time control mark, so I tried some approaches to developing my own, where you have to enter the value in question, the min value and the maximum value, so that the control panel returns true if the value is between two endpoints.

My first approach was to be able to compare ints, and it looked like this:

template<int Val, int LoEnd, int HiEnd> struct is_in_interval : public std::integral_constant<bool, Val >= LoEnd && Val <= HiEnd>::type {}; 

The function call will look like

 bool inside = is_in_interval<3, 1, 10>::value; 

and it seemed to work. I could even compromise it at compile time if the lower end was higher than the upper:

 template<int val, int LoEnd, int HiEnd> struct is_in_interval : public std::integral_constant< typename std::enable_if<LoEnd <= HiEnd, bool>::type, val >= LoEnd && val <= HiEnd>::type {}; 

To be able to compare any value, I came up with the following:

 template<typename T> struct is_in { template<T val, T LoEnd, T HiEnd> struct closed_interval : public std::integral_constant< typename std::enable_if<LoEnd <= HiEnd, bool>::type, val >= LoEnd && val <= HiEnd>::type {}; }; 

Now, however, the challenges have become more obscure:

 bool inside = is_in<int>::closed_interval<3,1,10>::value; 

but I still had the ability to use enable_if and could even add more (e.g. for checking is_integral).

My question is, is it possible to somehow make this generalized version easier to call, perhaps by deducing type (int) from non-type (3,1,10) above?

In the side I can use:

 template<typename T> constexpr bool isInInterval3(T val, T LoEnd, T HiEnd) { return val >= LoEnd && val <= HiEnd; } 

but in this function, I don’t think I can use a line like std::enable_if to say that LoEnd <= HiEnd .

+6
source share
1 answer

You can specify both "typename T" and other parameters in one template:

 template<typename T, T val, T LoEnd, T HiEnd> struct is_in_interval : public std::integral_constant< typename std::enable_if<LoEnd <= HiEnd, bool>::type, val >= LoEnd && val <= HiEnd>::type {}; 

Then you can define the in_interval macro only with the val, LoEnd and HiEnd parameters that will call is_in_interval with the first template parameter, for example decltype(val) :

 #define in_interval(val, LoEnd, HiEnd) (is_in_interval<decltype(val), val, LoEnd, HiEnd>::value) 

And you can use it as follows:

 cout << in_interval(3, 1, 10) << endl; 

It all works on my VS2012

0
source

Source: https://habr.com/ru/post/979523/


All Articles