C ++ How to make a template <T> f () return -1 for integral T, nullptr for pointer type

I need to do the following:

template<typename T>
f() {
    :
    return { -1 if T is of integral type, else nullptr }
}

In my specific use case, T can be one of four types:

int
Py_ssize_t  // ssize_t
Py_hash_t   // ssize_t

PyObject*   // PyObject is some C struct

This is the best solution I have so far:

template<typename T>
T test(typename enable_if<is_integral<T>::value, void*>::type = nullptr)
{ return -1; }

template<typename T>
T test(typename enable_if<is_pointer<T>::value, void*>::type = nullptr)
{ return nullptr; }

ideone

But is it really using a sledgehammer to crack a nut?

My only objection is that it solves a wider range of problems, but I'm not sure if it completed without additional attempts with std :: decay.

I'm used to resisting the temptation to complicate the code so that it can also solve imaginary extensions of the problem area at hand.

But in this case, I do not see a simpler solution.

+4
source share
4

, enable_if :

template <typename T>
typename std::enable_if<is_integral<T>::value, T>::type
test() {
    return -1;
}

template <typename T>
typename std::enable_if<is_pointer<T>::value, T>::type
test() {
    return nullptr;
}
+2

. :

template<typename T>
T f() { return std::is_integral<T>::value ? T(-1) : T(0); }

T(-1), T , undefined , , .

+4

template<typename T>
T f() { return -1; }

template<>
PyObject* f<PyObject*>() { return nullptr; }
+3
template<class T>
T f2(std::true_type /* is integral */){return -1;}
template<class T>
T f2(std::false_type /* is integral */){return nullptr;}
template<class T>
T f(){ return f2(std::is_integral<T>{}); }

, .

f2 .

SFINAE.

SFINAE , decltype auto f3, . .

+3

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


All Articles