R. Clayton (rclayton@monmouth.edu)
(no date)
During last night's lecture I talked about relational type traits for
determining various relations between types.
I was cleaning out my 509 directory and found the little gem shown below. It
implements the "is parent of" relational type-trait, which is a boolean
relation between two types. The code is not written in the style of the
proposed type-traits standard, but it does use the various mechanisms exploited
by type traits. This code brakes the g++ compiler; it does compile correctly
on solaris CC and (oddly enough) Microsoft C++ 6.0.
I'll leave it up to you, during those lazy summertime hours, to figure out what
this code does and how it works.
--$ cat parentof.cc #include <iostream>
template < class p, class c > struct is_parent_of {
struct yes { }; struct no { int i; };
static yes Test(p *); static no Test(...);
public:
enum { isparentof = sizeof(Test(reinterpret_cast<c *>(0))) == sizeof(yes) }; };
struct parent { };
struct child : parent { };
int main() { typedef is_parent_of<parent, child> pc; typedef is_parent_of<child, parent> cp;
std::cout << pc::isparentof << "\n"; std::cout << cp::isparentof << "\n"; }
$ CC parentof.cc
$ ./a.out 1 0
$ g++ ~/parentof.cc parentof.cc: In instantiation of `is_parent_of<parent, child>': parentof.cc:29: instantiated from here parentof.cc:29: invalid use of undefined type `struct is_parent_of<parent, child>' parentof.cc:5: forward declaration of `struct is_parent_of<parent, child>' parentof.cc: In instantiation of `is_parent_of<child, parent>': parentof.cc:30: instantiated from here parentof.cc:30: invalid use of undefined type `struct is_parent_of<child, parent>' parentof.cc:5: forward declaration of `struct is_parent_of<child, parent>'
$
This archive was generated by hypermail 2.0b3 on Fri May 10 2002 - 12:45:04 EDT