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.
You can apply the explicit function specifier to the definition of a user-defined conversion function to inhibit unintended implicit conversions from being applied. Such conversion functions are called explicit conversion operators.
The type cast operator converts the data type of expr to the type specified by type-name : [ type-name ] expr. Explicit type conversions require the type cast operator. Implicit type conversions are performed automatically by 4Test and do not require explicit type casting.
A cast is a special operator that forces one data type to be converted into another. As an operator, a cast is unary and has the same precedence as any other unary operator. const_cast<type> (expr) − The const_cast operator is used to explicitly override const and/or volatile in a cast.
The Implicit Operator According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting.
Yes and No.
It depends on which version of C++, you're using.
explicit
type conversion operatorsExample,
struct A { //implicit conversion to int operator int() { return 100; } //explicit conversion to std::string explicit operator std::string() { return "explicit"; } }; int main() { A a; int i = a; //ok - implicit conversion std::string s = a; //error - requires explicit conversion }
Compile it with g++ -std=c++0x
, you will get this error:
prog.cpp:13:20: error: conversion from 'A' to non-scalar type 'std::string' requested
Online demo : http://ideone.com/DJut1
But as soon as you write:
std::string s = static_cast<std::string>(a); //ok - explicit conversion
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:
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With