jeudi 2 juillet 2015

Direct-initializing an object inside a condition

It is possible to define and copy-initialize a variable inside the condition of an if statement :

if(int i = 17) { ... }

This also works with user-defined types, given that they overload operator bool :

if(Foo f = 42)      { ... }
if(Foo f = Foo(43)) { ... }

Why can't I use direct-initialization, like the following ?

if(Foo f(51)) { ... }

GCC emits error: expected primary-expression before 'f'.

Live on Coliru

Is there a reason other than "because the grammar says so" ? And how can I work around it ?

I'm working with VC++03, where Foo :

  • is a RAII-sensitive object, for which I took care not to define a copy constructor
  • is a template takingarguments from the user
  • has a two-parameters constructor

... so I'd rather avoid copying it or repeating its type.

Aucun commentaire:

Enregistrer un commentaire