Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #271 Test for type extension

If a variable x passed to procedure tst is of type foo, print "Same type." If it is of a type that extends foo, print "Extends type." If it is neither, print "Not related."

use v5.10;
sub tst {
    my ($x) = @_;

    if ( $x->isa('Foo') ) {
        say "Same type";
    }
    elsif ( $x->isa('FooExt') ) {
        my $issubclass = grep { $_ eq 'Foo' } @FooExt::isa;
        say $issubclass ? "Extends type" : "Same type";
    }
    else {
        say "Not related"
    }
}

To determine whether a FooExt object inherits from class Foo, we look for Foo in the @isa list. See demo for class definitions.
#include <iostream>
#include <type_traits>
template<typename T>
void tst(T)
{
    using namespace std;

    // Strip away any references and pointer
    typedef remove_const<remove_pointer<decay<T>::type>::type>::type D;

    if(is_same<D, foo>::value)
    {
        cout << "same type" << endl;
    }
    else if(is_base_of<foo, D>::value)
    {
        cout << "extends type" << endl;
    }
    else
    {
        cout << "not related" << endl;
    }
}

New implementation...
< >
tkoenig