Reputation: 24039
Can the user define how primitives cast between primitives? Or how they cast to user-defined types? ("Implicit casting constructor"? yikes)
This is a hypothetical question and it's hard to imagine a usage but perhaps one might want to affect how ints cast to bool.
Upvotes: 1
Views: 1772
Reputation: 72479
Can the user define how primitives cast between primitives?
No. The language is not mutable.
Or how they cast to user-defined types? ("Implicit casting constructor"? yikes)
Yes:
struct X {
X() {}
X(int a) {} // implicit cast
};
X x;
x = 10; // int implicitly cast to X
Upvotes: 1
Reputation: 477030
You can't change how built-in types behave. You're not allowed to break the language like that, much like you cannot overload a new operator+
for int
s that does something else.
The language needs to be able to make certain basic guarantees so that libraries can be written that can rely on basic behaviour!
You can convert any type to a user-defined type by providing a constructor that's callable with one argument, e.g.:
struct Foo
{
Foo(T const &);
// ...
};
Now you can say, T x; Foo y = x;
etc.
You can also do the reverse and provide conversions from your class:
struct Foo
{
operator S() const;
// ...
};
Now you can also say, S s = y;
.
Upvotes: 8
Reputation: 206528
You cannot change how primitives cast to other primitives.
You can define how user defined types can be cast to primitive types/any type by providing a conversion constructor.
Upvotes: 2