Comparison of template parameter comparison time

I have a requirement that I use a specific class if the integer passed as one of the template parameters is greater than a certain value. Otherwise, I should get a compile-time error ...

This is something like the following:

enum Time { Day, Week, Month };

template<Time t, int length>
class Timer
{
}

Now I need to limit the instantiation Timerin such a way that -

Timer<Day,8>, Timer<Day,9>etc., but lengthcannot be less than 8 when used with Day.

Similarly, lengthit cannot be less than 10 when used with Week, etc.

Can someone please help me on how this can be achieved at compile time?

+5
source share
5

length >= 8 bool . true. , , .

hth.

+6

, , , :

template<Time t, int length>
class Timer
{
    static_assert( (t == Day && length > 7) 
                 ||(t == Week && length > 10)
                 ||(t == Month && length > 99), "Invalid parameters"
};

, , / .

SFINAE : , : , Timer<Day,5> ? , Timer<Time,int>!

EDIT: static_assert ++ 0x, ++ 0x static_assert :

#define static_assert( cond, name ) typedef char sassert_##name[ (cond)? 1 : -1 ];

, . :

static_assert( sizeof(int)==4, InvalidIntegerSize ) )

, ( ), sassert_InvalidIntegerSize .

+7

:

template<bool> 
struct rule;

template<> 
struct rule<true> {};

template<Time Tm, int Len>
struct constraint;

//Rule for Day     
template<int Len>
struct constraint<Day, Len> : rule<(Len>= 8)>
{};

template<Time Tm, int Len>
class Timer : constraint<Tm, Len>
{
   //your code
};

:

int main() {
        Timer<Day, 7> timer1; //error 
        Timer<Day, 8> timer2; //okay
        return 0;
}

-:


Week Month :

//Rule for Week
template<int Len>
struct constraint<Week, Len> : rule<(Len>= 10)>
{};

//Rule for Month
template<int Len>
struct constraint<Month, Len> : rule<(Len>= 100)>
{};
+3

, , .

template <typename T, size_t V>
class Foo
{
  static_assert(helper<T,V>::value, "Wrong Parameters");
};

:

// Require full specialization
template <typename T, size_t V> struct helper: std::false_type {};

template <>
struct helper<Bar,0>: std::true_type {};

template <>
struct helper<Bar,4>: std::true_type {};


// Property like
template <typename T, size_t V> struct helper: std::false_type {};

template <size_t V>
struct helper<Bar, V>: std::integral_constant<bool, V <= 8> {};

, ++ 0x. ++ 03 true_type, false_type integral_constant.

+2
enum Time { Day, Week, Month };
template<Time T> struct Length;
template<> struct Length<Day> { static const int value = 8 ; };
template<> struct Length<Week> { static const int value = 9; };
template<> struct Length<Month> { static const int value = 10; };

template<bool b> struct Limit;
template<> struct Limit<true> { typedef bool yes; };

#define COMPILE_ASSERT(V) typedef typename Limit<(V)>::yes checked

template<Time t, int length>
class Timer
{
  COMPILE_ASSERT(length >= Length<t>::value);
};

.

0

All Articles