dimanche 3 mai 2015

How to disable implicit constructor conversion, while allowing copy-initialization

Assuming we have something like:

class U {
  ...
}

and:

class T {
  T(const U&) { ... }
}

Now I can declare a variable like so: T blah(U()); or T blah = U()

Personally I prefer the later.

Now, should I change the T copy constructor to:

class T {
  explicit T(const U&) { ... }
}

I can only declare a variable like: T blah(U()); T blah = U(); will give me a compilation error about the impossibility to convert U to T.

http://ift.tt/1niiMSi explains that behaviour with: "Specifies constructors and (since C++11) conversion operators that don't allow implicit conversions or copy-initialization."

Now, the folks I work for require that all our constructors are made explicit. Being an old fart, I don't like changing my coding style too much and forget about T blah = ... style.

The question as such is this: "Is there a way to make a constructor explicit while allowing copy-initialization syntax?"

There are very good reasons to make a constructor explicit, and most of the time, you do want to make it explicit.

Under those instances, I thought I could do something along the line of:

class T {
  template<typename = V>
  T(const V&) = delete;
  T(const U&) { ... }
}

Which would be a catch-all constructor forbidding all conversion but the one I actually want.

Was wondering if there was some trick I could use.

Thanks

Aucun commentaire:

Enregistrer un commentaire