I wonder if there is a possibility in c++ to achieve the same cast overloading like in this C# example:
class A {
public static implicit operator A(string s) {
return new A();
}
public static implicit operator A(double d) {
return new A();
}
static void Main(string[] args) {
A a = "hello";
A b = 5.0;
}
}
In C++ it should be something like this:
#include <string>
using namespace std;
class A{
/*SOME CAST OVERLOADING GOES HERE*/
};
void main(){
A a = "hello";
A b = 5.0;
}
Can you help me how I can make this cast overloading?
This is typically achieved with constructors:
Usage:
A a("hello"), b(4.2), c = 3.5, d = std::string("world");(If you declare the constructor
explicit, then only the first form (“direct initialization”, with the parentheses) is allowed. Otherwise the two forms are entirely identical.)A one-parameter constructor is also called a “conversion constructor” for this very reason: You can use it to construct an object from some other object, i.e. “convert” a
double, say, to anA.Implicit conversion is widely used. For example, it’ll apply in the following situation:
This constructs temporaries
A(1.5)andA("hello")and passes them tof. (Temporaries also bind to constant references, as you can see with the second argument.)Update: (Credits to @cHao for looking this up.) According to the standard (12.3.4), “At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.” (This refers to implicit conversion; direct-initialization a la
A a("hello");doesn’t fall under this*. See this related question.) So unfortunately you cannot sayf("hello", "world");. (Of course you can add aconst char *constructor, which in the new C++11 you can even forward to the string constructor with almost no effort.)*) I think this is actually a bit more subtle. Only user-defined conversions are affected by the rule. So first off, you get a fundamental conversion from
char (&)[6]toconst char *for free. Then you get one implicit conversion fromconst char *tostd::string. Finally, you have an explicit conversion-construction fromstd::stringtoA.