Assuming we have something like:
class U { ... }
and
class T { T(const U&) { ... } }
Now I can declare a variable as follows: U foo; , then T blah(foo); or T blah = foo
Personally, I prefer later.
Now, do I need to change the T-copy constructor to:
class T { explicit T(const U&) { ... } }
I can declare a variable as: T blah(foo); T blah = foo; will give me a compilation error about the impossibility of converting U to T.
http://en.cppreference.com/w/cpp/language/explicit explains that behavior with: "Defines constructors and (since C ++ 11) conversion operators that do not allow implicit conversions or copy-initialization ."
Now for those for whom I work, it is required that all our constructors be explicit. Being an old fart, I donβt like to change the coding style too much and forget about the T blah style ...
The question as such is: "Is there a way to make the constructor explicit by allowing copy initialization syntax?"
There are very good reasons to make the constructor explicit, and most of the time you do want to make it explicit.
In these cases, I thought I could do something along the line:
class T { template<typename = V> T(const V&) = delete; T(const U&) { ... } }
What will be the catch-all constructor that prohibits all conversions, but the one I really want.
I wonder if there is any trick that I could use.
thanks
Edit: fixed the typo as Matt McNabb pointed out. thanks