This question already has an answer here:
In C++11, to find out whether a class has a member function size
, you could define the following test helper:
template <typename T>
struct has_size_fn
{
typedef char (& yes)[1];
typedef char (& no)[2];
template <typename C> static yes check(decltype(&C::size));
template <typename> static no check(...);
static bool const value = sizeof(check<T>(0)) == sizeof(yes);
};
Is there a similar trick for doing this in C++98 without relying on compiler extensions such as typeof
?
Yes:
Actually, your detection is potentially erroneous.
The problem is that all you are detecting is that
C
has a membersize
:If you wish to harden the detection, you should attempt to detect only the right
size
(for whatever right is). Here is such a hardened detection.Edit: with overloads.
The trick to deal with incorrect
size
members is thereally_has
structure. I make no pretense that it is perfect, though...In C++11, things are simpler (though no less verbose) because you can detect things by use directly. The equivalent trait is thus:
However, the recommended method in C++ is not to use traits if you can; in functions for example you can use
decltype
right in the type signature.