How to overload member function based on pointer versus type without pointer

Given the following situation:

template <typename T>
class Whatever
{
public:
    Whatever(T &&t): _t(std::move(t)) { }

private:
    T _t;
};

When Tis a pointer type, I need to check the Targ constructor to see if it -1(don't ask) and change it to nullptrbefore assigning it _t. In other words , I need to overload this constructor for pointer types.

Does anyone know if this is possible?

Note. Even if I partially specialize the class on pointer types, I would like this class to inherit from the class itself, if possible (since the behavior of both classes is identical, except for this), but I don’t know, it is possible. Any help would be greatly appreciated. Thanks.

+4
2

:

#include <type_traits>

template <typename T>
class Whatever
{
public:
    Whatever(T&& t)
        : Whatever(std::move(t), std::is_pointer<T>{})
    {
    }

private:
    Whatever(T&& t, std::true_type)
        : _t(/*initialize _t as a pointer*/)
    {
    }

    Whatever(T&& t, std::false_type)
        : _t(/*initialize _t as a non-pointer*/)
    {
    }

    T _t;
};
+5

std::enable_if<...> . -:

template <typename T>
class WhateverBase {
protected:
    T _t;
    WhateverBase(T&& t): _t(std::move(t)) {}
};
template <typename T>
class WhateverBase<T*> {
protected:
    T* _t;
    WhateverBase(T* t): _t(adjust(t)) {}
};
template <typename T>
class Whatever: WhateverBase<T>
{
public:
    Whatever(T&& t): WhateverBase(std::move(t)) {}
    // ...
};

Whatever, T .

move(), :

template <typename T>
std::remove_reference_t<T>&& adjust_move(T&& ref) {
    return static_cast<std::remove_reference_t<T>&&>(ref);
}
template <typename T>
T* adjust_move(T* ref) { return adjust(ref); }

Whatever<T>::Whatever(T&& t): _t(adjust_move(t)) {}

( ...).

... std::move(t) .

+3

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


All Articles