VS 2013, C++: STL changes to meet C++/11 specs, Explicit conversion operators

Explicit conversion operators <<Link

  • C++ allows explicit type conversion using syntax similar to the function-call syntax.
  • Form: simple-type-name ( expression-list )
  • A simple-type-name followed by an expression-list enclosed in parentheses constructs an object of the specified type using the specified expressions. The following example shows an explicit type conversion to type int:
  • ISO/IEC paragraph: Paragraph 12.3 Conversions
  • See also: https://www.stroustrup.com/C++11FAQ.html#explicit-convertion

Example from Stroustrup so it runs in a console app in VS 2013, just open a VS 2013 Console app, copy the code below and then drop it into an empty console app or however you want to run it:

/*********Start copy here *******************/

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
     struct S { S(int) { } };

    struct SS {
        int m;
         SS(int x) : m(x) { }
        explicit operator S() { return S(m); }  // because S don't have S(SS)
    };

    SS ss(1);
     //S s1 = ss;    // error; like an explicit constructor
    S s2(ss);    // ok ; like an explicit constructor
    void f(S);
    //f(ss);        // error; like an explicit constructor

}

/*******End copy here *********************/

 

-