Skip to content

Instantly share code, notes, and snippets.

@Bktero
Last active July 27, 2017 07:45
Show Gist options
  • Save Bktero/059d648e2354781f8629ab00f103e4d8 to your computer and use it in GitHub Desktop.
Save Bktero/059d648e2354781f8629ab00f103e4d8 to your computer and use it in GitHub Desktop.
[C++11] Example of conversion operators
#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'
}
}
}
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