Apr 22, 2024 at 10:52pm UTC
why does this code determine if the type is a class:
1 2 3 4 5 6 7 8
template <typename T>
class is_class
{
template <typename C> static char test(int C::*);
template <typename C> static int test(...);
public :
static constexpr bool value = sizeof (test<T>(0) == 1);
};
since a class may have no members and especially no integral members
e.g.
1 2 3 4
struct A
{
};
std::cout << is_class<A>::value << std::endl;
A has no member variables and yet it reports that it is a class!
Regards,
Juan
Last edited on Apr 22, 2024 at 10:53pm UTC
Apr 23, 2024 at 1:48am UTC
It isn’t testing whether there are any members, only if the type conforms to a class, which may have members.
I don’t know where you got that snippet from, but it usually appears in the context of SFINAE explanations. You should go reread it. (Or find a better read.)
Apr 23, 2024 at 11:44am UTC
Is the last closing parenthesis in the wrong place in line 7 of the initial post? It seems to me the line should be
static constexpr bool value = sizeof (test<T>(0)) == 1
If not, I'm confused why it's taking the size of a bool and then casting that size_t value back to another bool.
Apr 23, 2024 at 2:07pm UTC
Yes, it is in the wrong spot.