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; }
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
4