Logo

Programming-Idioms

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."
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#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;
    }
}
public static void tst(Object x) {
  if (x.GetType() == typeof(foo))
    Console.WriteLine("Same type.");
  else if (x.GetType().IsAssignableTo(typeof(foo)))
    Console.WriteLine("Extends type.");
  else
    Console.WriteLine("Not related.");			
}
tst(x) {
  if (x.runtimeType == Foo) {
    print("Same Type.");
  } else if (x is Foo) {
    print("Extends type.");
  } else {
    print("Not related.");
  }
}
  subroutine tst (x)
    class (*), intent(in) :: x
    type (foo) :: y
    if (same_type_as (x,y)) then
       write (*,'(A)') "Same type."
    else if (extends_type_of (x,y)) then
       write (*,'(A)') "Extends type."
    else
       write (*,'(A)') "Not related."
    end if
  end subroutine tst
uses classes;
procedure tst(x: tobject);
begin
  if x.ClassType = foo then
    writeln('Same type')
  else if x is foo then
    writeln('Extends type')
  else
    writeln('Not related');
end; 
def tst(x):
    if isinstance(x, foo):
        print("Same type.")
    elif issubclass(type(x), foo):
        print("Extends type.")
    else:
        print("Not related.")