Last active
July 27, 2017 07:45
-
-
Save Bktero/059d648e2354781f8629ab00f103e4d8 to your computer and use it in GitHub Desktop.
[C++11] Example of conversion operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
class FilePath | |
{ | |
public: | |
explicit FilePath(string filename) : | |
filename_m(filename), | |
exists_m(filename_m[0] == 'E') | |
{ | |
} | |
explicit operator bool() const | |
{ | |
cout << "operator bool()" << endl; | |
return exists_m; | |
} | |
operator string() const | |
{ | |
cout << "operator string()" << endl; | |
return filename_m; | |
} | |
private: | |
string filename_m; | |
bool exists_m; | |
}; | |
int main() | |
{ | |
if (FilePath path = FilePath("Enable.txt")) | |
{ | |
string message = path; | |
message += " exists"; | |
// Or: string message = (string) path + " exists"; | |
// Or: string message = string(path) + " exists"; | |
cout << message << endl; | |
//if (path == 1) | |
{ | |
// Not possible because 'operator bool()' is marked as 'explicit' | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
operator bool() | |
operator string() | |
Enable.txt exists |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment