mirror of
https://github.com/boostorg/convert.git
synced 2026-02-18 01:52:22 +00:00
48 lines
2.1 KiB
Plaintext
48 lines
2.1 KiB
Plaintext
[section:convert_default_constructible The ['Default Constructible] Type Requirement]
|
|
|
|
In order for a type to be integrated into the ['boost::lexical_cast] framework that type needs to be ['Default Constructible]. Deeply in the bowels of the implementation a temporary-storage instance of the Target type is created and then populated with the conversion result. The ['boost::lexical_cast] implementation chooses the default constructor to create such an instance. For more details see __ref_1__.
|
|
|
|
['boost::convert] also creates a temporary-storage instance of the Target type that the plugged-in converter then populates with the conversion result. By default that temporary-storage is created by
|
|
|
|
namespace boost
|
|
{
|
|
template<class TypeOut>
|
|
TypeOut
|
|
convert<TypeOut>::create_storage()
|
|
{
|
|
return TypeOut();
|
|
}
|
|
}
|
|
|
|
and, therefore, the ['Default Constructible] requirement is also the default requirement of ['boost::convert].
|
|
|
|
A well-designed type (in my opinion, anyway) should only have meaningful and unambiguous constructors... and the default constructor is not necessarily one of them. Consider the following ['direction] type as one such example. The type has only two meaningful states and is not ['Default Constructible]:
|
|
|
|
struct direction
|
|
{
|
|
enum value_type { up, dn };
|
|
direction(value_type value) : value_(value) {}
|
|
private: value_type value_;
|
|
};
|
|
|
|
For such a type the call below will not compile (due to the ['Default Constructible] requirement):
|
|
|
|
direction dir1 = lexical_cast<direction>(str); // Does not compile
|
|
direction dir2 = convert<direction>::from(str).value(); // Does not compile
|
|
|
|
However, ['boost::convert] will be able to handle such a type with little help from the user. What ['boost::convert] needs is the instructions ['how] to create that mentioned temporary-storage:
|
|
|
|
namespace boost
|
|
{
|
|
template<> inline direction convert<direction>::create_storage()
|
|
{
|
|
return direction(direction::up);
|
|
}
|
|
}
|
|
|
|
Now the conversion code compiles:
|
|
|
|
direction dir2 = convert<direction>::from(str).value(); // Compiles
|
|
|
|
[endsect]
|