Constrain your user-defined conversions -- Jonathan Mueller

jonathanmueller.pngSometimes you want to add an implicit conversion to a type. This can be done by adding an implicit conversion operator. For example, std::string is implicitly convertible to std::string_view.

Constrain Your User-Defined Conversions

By Jonathan Mueller

From the article:

Sometimes you want to add an implicit conversion to a type. This can be done by adding an implicit conversion operator. For example, std::string is implicitly convertible to std::string_view:

	class string { // template omitted for simplicity
	public:
	    operator std::string_view() const noexcept
	    {
	       return std::string_view(c_str(), size());
	    }
	}; 

The conversion is safe, cheap, and std::string and std::string_view represent the same platonic value — we match Tony van Eerd’s criteria for implicit conversions and using implicit conversions is justified.

However, even when all criteria are fulfilled, the conversion can still be dangerous.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.