Re: boost::any: explicit constructor?

From: Kevlin Henney [mailto:kevlin@curbralan.com]
I have yet to see a convincing reason to make it explicit. Autoboxing has been a part of boost::any's design from day 1, which existed before Boost -- and, indeed, the "autoboxing" terminology. Supporting such conversions was intentional. There is no more reason to make the converting constructor of boost::any explicit than there is to make the converting constructor of std::string explicit, or the conversion from int to long explicit, or the conversion from T * to void *, or indeed any other widening conversion.
Perhaps you could add this design decision as a FAQ in the documentation for any? Something like this (assuming a faq.xml among the any docs): <qandaentry> <question><para>Why isn't the parameterized constructor for <classname>boost::any</classname> explicit?</para></question> <answer> <para>The most important reason is that <classname>boost::any</classname> favors the convenience of implicit widening conversions over the additional safety of an explicit constructor. This design decision is fundamental for <code><classname alt="boost::any">any</classname></code>, so making the constructor explicit would require very convincing reasons. </para> <para>One useful idiom when the implicit construction of <code><classname alt="boost::any">any</classname></code> is considered a problem is to always pass <classname>boost::any</classname> by reference rather than by reference to <code>const</code>, or by value. This avoids implicit conversions of arguments to functions accepting <classname>boost::any</classname>. For example, the following example shows how to disable autoboxing for calls to the function <code>sample</code>: </para> <programlisting name="any.faq.pass_by_reference">void sample(boost::any& a) {} int main() { boost::any a(5); sample(a); // This works sample(5); // This won't compile }</programlisting> </answer> </qandaentry> If you like it, I'll update the docs. Bjorn
participants (1)
-
Bjorn.Karlsson@readsoft.com