Assuming we have something like:
class U {
...
}
and:
class T {
T(const U&) { ... }
}
Now I can declare a variable like so:
U foo;
then T blah(foo);
or T blah = foo
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(foo);
T blah = foo;
will give me a compilation error about the impossibility to convert U to T.
http://en.cppreference.com/w/cpp/language/explicit 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
Edit: corrected the typo as pointed by Matt McNabb answer. thanks