Visual C++2012でExplicit conversion operatorsを試す
VC++2012のNovember CTP of the C++ compilerお試しその4。
Explicit conversion operatorsを試します。
というか、「Explicit conversion operators」ってどんな機能なのよ?
そのままの意味でconversion operatorsをexplicitにできるということでよいのかしら。
#include <iostream> class Int { int value_; public: explicit Int(int val = 0) : value_(val) {}; int value() const { return value_; } explicit operator int() const { std::cout << "operator int" << std::endl; return value_; } operator double() const { std::cout << "operator double" << std::endl; return value_; } }; void printi(int val) { std::cout << val << std::endl; } void printd(double val) { std::cout << val << std::endl; } int main() { Int a(1); //printi(a); // explicitなのでInt → intの暗黙変換できません。 printi(static_cast<int>(a)); printd(a); // Int → doubleの暗黙変換は可能 return 0; }
Int → intの変換はexplicitをつけてあるので暗黙変換はできず、Int → doubleの変換はexplicitをつけてないので暗黙変換可能です。
同様のことをC#でやると以下。
class Int { public Int(int val) { value_ = val; } public static explicit operator int(Int val) { Console.WriteLine("operator int"); return val.value_; } public static implicit operator double(Int val) { Console.WriteLine("operator double"); return val.value_; } private int value_; } class Program { static void printi(int val) { Console.WriteLine(val); } static void printd(double val) { Console.WriteLine(val); } static void Main(string[] args) { var val = new Int(1); //printi(val); // Int → intは暗黙変換できません。 printi((int)val); printd(val); // Int → doubleの暗黙変換は可能 } }