C ++ templates and the ambiguity problem

I have a subset of the pointer class that looks like this:

template <typename T>
struct Pointer
{
     Pointer();
     Pointer(T *const x);
     Pointer(const Pointer &x);
     template <typename t>
     Pointer(const Pointer<t> &x);

     operator T *() const;
};

The purpose of the last constructor is to allow the Pointersubclass or basically any type that can be implicitly converted to T *. This actual rule applies only in the constructor definition, and the compiler cannot actually understand this only in the declaration. If I omit it and try to pass it Pointer<Sub>to the constructor Pointer<Base>, I get a compilation error, despite the possible path through operator T *().

While he solves the above problem, he creates another. If I have an overloaded function in which one overload takes Pointer<UnrelatedClass>and the other takes Pointer<BaseClass>, and I try to call it with Pointer<SubClass>, I get ambiguity between the two overloads, with the intention, of course, that the last overload will be called.

Any suggestions? (Hope I was clear enough)

+3
source share
2 answers

The treatment for your problem is called SFINAE (replacement failure is not an error)

#include "boost/type_traits/is_convertible.hpp"
#include "boost/utility/enable_if.hpp"

template<typename T>
class Pointer {
   ...
   template<typename U>
   Pointer(const Pointer<U> &x,
      typename boost::enable_if<
         boost::is_convertible<U*,T*>
      >::type* =0)
   : ...
   {
     ...
   }
   ...
};

U * T *, enable_if typedef type void. . U * T *, typedef , .

.

: is_convertible :

typedef char one;         // sizeof == 1  per definition
struct two {char c[2];};  // sizeof != 1

template<typename T, typename U>
class is_convertible {
    static T source();
    static one sink(U);
    static two sink(...);
public:
    static const bool value = sizeof(sink(source()))==1;
};
+6

, :

 template <typename t>
 explicit Pointer(const Pointer<t> &x);

/ operator T *() const; - , .

std:: auto_ptr . , .

0

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


All Articles