Logo

Programming-Idioms

  • VB
  • Obj-C
  • Ruby
  • Perl

Idiom #73 Create a factory

Create a factory named fact for any sub class of Parent and taking exactly one string str as constructor parameter.

use Safe::Isa;
sub fact {
    my ($class, $str) = @_;
    return $class->new($str) if $class->$_isa('Parent');
}
def fact(klass, str)
  klass.new(str) if klass.is_a?(Parent)
end
#include <string>
#include <type_traits>
template <typename T,
          std::enable_if_t<
            std::is_base_of_v<Parent, T>, bool> = true>
T fact(const std::string& str) {
  return T(str);
}

New implementation...
< >
bbtemp