C++ (Part3)

Posted on at


You will have to define the type yourself, it will probably be something like the following:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class only_int

{

  int val_;

 

public:

  only_int (int v = 0) : val_(v) {}

   

  template <typename T, ENABLE_IF(is_signed_integral<T>)> 

    only_int (T v) : val_(v) {} // can static_assert the size

   

  template <typename T, ENABLE_IF(!is_signed_integral<T>)>

    only_int (T) = delete;

 

  int get() const { return val_; }

};

is_signed_integral is a type trait I have defined for describing signed integral types:

1

2

3

4

5

6

template <typename T>

using is_signed_integral = typename std::conditional<

  std::is_signed<T>::value && std::is_integral<T>::value,

  std::true_type,

  std::false_type

>::type;

ENABLE_IF is a macro I defined to make the code that uses enable_if tricks more concise. This syntax works in C++11, and the macro is defined as:

1

2

3

# define ENABLE_IF(...)                                   \

  typename std::enable_if<__VA_ARGS__::value, bool>::type \

    = true

The idea behind the three constructors of only_int is the following. The first constructor simply works when an int is used for copy construction. The second and third constructor declarations provide a ‘conditional’ constructor definition. If condition is_signed_integralis satisfied, the object is properly initialized. Otherwise, e.g., when copy-initializing from adouble constructor is declared as deleted: a compile-time error is triggered.



About the author

toshi-warraich

Good Boy with very bad thoughts.

Subscribe 0
160