How to check at compile time if Default Constructor for a class exists?

Adam D. Ruppe via Digitalmars-d digitalmars-d at
Fri Jan 1 08:13:47 PST 2016

On Friday, 1 January 2016 at 15:55:53 UTC, Bottled Gin wrote:
> That gives me a false positive if a defined constructor has 
> default value for all its arguments.

I thought that counted as a default constructor...

But if not, you could also try this on for size:

template HasDefaultConstructor(Class) {
	bool helper() {
		foreach(overload; __traits(getOverloads, Class, "__ctor")) {
			static if(__traits(compiles, { Class function() ctor = 
&overload; }))
				return true;

		return false;

	enum HasDefaultConstructor = helper();

The helper loops through all the overloads looking for one that 
is assignable to a zero-arg pointer - meaning it matches the 
default signature, ignoring default params.

Then it just returns if it found one.

More information about the Digitalmars-d mailing list