Can the translation operator be explicit?

When it comes to constructors, adding the explicit keyword prevents the enthusiastic compiler from creating an object, unless that was the first intention of the programmers. Is such a mechanism available to casting operators?

 struct Foo { operator std::string() const; }; 

Here, for example, I would like to use Foo in std::string , but I do not want such an order to be executed implicitly.

+75
c ++ casting explicit operator-keyword
Nov 23 2018-11-11T00:
source share
1 answer

Yes and No.

It depends on which version of C ++ you are using.

  • C ++ 98 and C ++ 03 do not support explicit type conversion operators
  • But C ++ 11. does.

Example

 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 the 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, an explicit conversion operator is called a โ€œcontextual conversion operator" if it is converted to a logical one. Also, if you want to know more about implicit and explicit conversions, read this topic:

  • Implicit VS Explicit Conversion

Hope this helps.

+91
Nov 23 '11 at 8:55
source share



All Articles