Foreign Constructors--Gerard Meier

A nice technique to initialize complex objects simply with one constructor:

Foreign Constructors

by Gerard Meier

From the article:

Recently I found myself extending a game engine with font rendering support. Fonts have a lot of properties, so naturally I created a tidy structure to hold all parameters. Whenever drawing a piece of text: I'd simply pass this structure along.

A philosophy I follow, is one of programmer convenience. For example: I always specify default values; when you instantiate a class without any parameters, it is directly usable. Following from that, whenever you call an method or constructor - you should not have to specify not used parameters. This adds a practical issue: it requires all kinds of constructors...

 

Add a Comment

Comments are closed.

Comments (3)

0 0

NoSenseEtAl said on Aug 18, 2015 01:09 PM:

I usually do it with a lambda, without special constructor, problem is that before C++14 you had to do -> for lambdas whose body was not simple return statement.
0 0

TomJ said on Aug 20, 2015 01:52 AM:

This is a nice idea, I have come across this situation too. However, I don't see why you need to use std::function here. It would surely be simpler to instead make the Font constructor a template function, with a single template type parameter F defining for the type of the visit function. This would also (likely) be more efficient due to inlining.
1 0

Marco Arena said on Aug 28, 2015 06:54 AM:

As the other guys said, I think you can just:

struct Button {
const Font font = [] {
Font f;
f.a=10;
f.b=20;
return f;
}();
};


This way you don't add anything to your business class (adding complexity always results in maintaing and remembering that complexity).

But this is not my only concern: if you use std::function then the compiler is not able to inline the call and this *may be* a problem.