Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

c++ - Can a cast operator be explicit?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes and No.

It depends on which version of C++, you're 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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...