Reputation: 4845
I was reading http://bartoszmilewski.wordpress.com/2009/10/21/what-does-haskell-have-to-do-with-c/ and came across this code to check if a type is a pointer or not:
template<class T> struct
isPtr {
static const bool value = false;
};
template<class U> struct
isPtr<U*> {
static const bool value = true;
};
template<class U> struct
isPtr<U * const> {
static const bool value = true;
};
How do i specialize the general template to handle case for const pointer to a const type? If i do this:
std::cout << isPtr <int const * const>::value << '\n';
i get a true when i am expecting false. Can someone explain?
EDIT: using VC++ 2010 compiler (express :-)
Upvotes: 4
Views: 1573
Reputation: 70088
The result is coming correct only; your third specialization is invoked when you call isPtr <int const * const>
; which you are setting to true
.
You can choose enum
over bool
in this case as you have 3 states:
enum TYPE
{
NOT_POINTER,
IS_POINTER,
IS_CONST_POINTER
};
template<class T> struct
isPtr {
static const TYPE value = NOT_POINTER;
};
template<class U> struct
isPtr<U*> {
static const TYPE value = IS_POINTER;
};
template<class U> struct
isPtr<U * const> {
static const TYPE value = IS_CONST_POINTER;
};
Here is the demo.
Upvotes: 5