Template specialization to use default type if class member typedef does not exist
Posted
by Frank
on Stack Overflow
See other posts from Stack Overflow
or by Frank
Published on 2010-06-09T18:09:29Z
Indexed on
2010/06/09
18:12 UTC
Read the original article
Hit count: 140
Hi Everyone,
I'm trying to write code that uses a member typedef of a template argument, but want to supply a default type if the template argument does not have that typedef. A simplified example I've tried is this:
struct DefaultType { DefaultType() { printf("Default "); } };
struct NonDefaultType { NonDefaultType() { printf("NonDefault "); } };
struct A {};
struct B { typedef NonDefaultType Type; };
template<typename T, typename Enable = void> struct Get_Type { typedef DefaultType Type; };
template<typename T> struct Get_Type< T, typename T::Type > { typedef typename T::Type Type; };
int main()
{
Get_Type::Type test1; Get_Type::Type test2; }
I would expect this to print "Default NonDefault", but instead it prints "Default Default". My expectation is that the second line in main() should match the specialized version of Get_Type, because B::Type exists. However, this does not happen.
Can anyone explain what's going on here and how to fix it, or another way to accomplish the same goal?
Thank you.
© Stack Overflow or respective owner