When it comes to constructors, adding the keyword explicit prevents an enthusiastic compiler from creating an object when it was not the programmer’s first intention. Is such mechanism available for casting operators too?
struct Foo
{
operator std::string() const;
};
Here, for instance, I would like to be able to cast Foo into a std::string, but I don’t want such cast to happen implicitly.
Yes and No.
It depends on which version of C++, you’re using.
explicittype conversion operatorsExample,
Compile it with
g++ -std=c++0x, you will get this error:Online demo : http://ideone.com/DJut1
But as soon as you write:
The error goes away : http://ideone.com/LhuFd
BTW, in C++11, the explicit conversion operator is referred to as "contextual conversion operator" if it converts to boolean. Also, if you want to know more about implicit and explicit conversions, read this topic: