Logo

Programming-Idioms

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

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another Rust 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
auto fact(T, A...)(A a)
if (is(T==class) && is(T: Parent))
{
    return new T(a);
}
type ParentFactory func(string) Parent

var fact ParentFactory = func(str string) Parent {
	return Parent{
		name: str,
	}
}
def fact(a_class, str_):
    if issubclass(a_class, Parent):
        return a_class(str_)
def fact(klass, str)
  klass.new(str) if klass.is_a?(Parent)
end
type Parent = class
  constructor create(const str: string);
end;

type ClassOfParent = class of Parent;

function fact(ClassType: ClassOfParent; const str: string): Parent;
begin
  result := ClassType.Create(str);
end;
use Safe::Isa;
sub fact {
    my ($class, $str) = @_;
    return $class->new($str) if $class->$_isa('Parent');
}
class Parent {
    constructor(str) {}
    fact(new_class, str) {
        if (new_class.prototype instanceof Parent) {
            return new new_class(str)
        }
    }
}

class Child extends Parent {}
#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);
}