How to check if typedef is type for int

In C ++, I want to have a class whose constructors are as follows:

class A {
  explicit A(A* other) { ... }
  explicit A(intptr_t other) { ... }
};

The problem with this is that the user is initializing with

A a(0);

Then, on a 64-bit system, the compiler will complain that it does not know whether to convert 0to A*or to intptr_t, which is fair enough. Since I want this simple notation to work, I added the following constructor:

explicit A(int a) { assert(a==0); ... }

The statement is that it is the only whole for which it makes sense. Now the problem arises with a 32-bit system, in which intptr_tactually ... int! So, the system complains that there are two constructors that take the same type of parameter (which is again true).

, : , intptr_t int int. A a(0) int, ( ).

+5
5

-

#if INTPTR_MAX == INT_MAX

, , long int , ptrint_t - typedef long. ( , ) uintptr_t, intptr_t.

: , . - : int , boost::enable_if, , int. ptrint_t - int, , , . ptrint_t int, , int. (, : , boost::enable_if .)

+3

, , other 0? - , , ++ 11 boost:

class A { 
public:
    explicit A(A* other) { ... } 
    explicit A(intptr_t other) { ... } 

    template <class T>
    explicit A(T other)
    {
        static_assert(std::is_convertible<T, intptr_t>::value, "Could not convert value to intptr_t");
        static_assert(std::is_integral<T>::value, "Argument must be integral");
        intptr_t p = other;
        ...
    }
}; 

, ( , ), :

A a(0.0f);
+1

, 6 (int, long, long long ) intptr_t.

0

A a(0)

template.

class A {
public:
  template<typename T>
  explicit  A (T t) { assert(t==0); }  // explicit matters ?

  explicit A(A* other) { ... }
  explicit A(intptr_t other) { ... }
};

32- 64- !

-1

You can also pass a parameter that determines which one is called:

struct TakePtr{};
struct TakeInt{};

class A {
  A(A* other, const TakePtr&) { ... }
  A(intptr_t other, const TakeInt&) { ... }
};

This way you can verify which constructor is called:

A a2( 0, TakeInt() );     // calls the 2nd constructor, taking int
A a1( &a2, TakePtr() );   // calls the 1st constructor, taking a pointer
-1
source

All Articles