I am trying to support implicit casts of literal values in a type system. These implicit casts are intended and ideal (See note 1). I'm aware that C++ can perform multiple implicit casts in an expression. The second line of main
below does not work.
class A {
public:
A(const std::string&);
};
class B {
public:
B(const A&);
};
int main(void)
{
A("example"); // this works
B("example"); // this does not work
}
If I add a const char*
constructor to A, the second line works...
class A {
public:
A(const char*);
A(const std::string&);
};
class B {
public:
B(const A&);
};
int main(void)
{
A("example"); // this works
B("example"); // now it works
}
Why does the first implementation not work? The second line could construct the const char*
into a std::string
, then into a A
, and finally B
.
Note 1: The values of the types that are implicitly castable are the same values, the type only represents that the value has passed a pre-condition, holds it's condition through operations, and propogates that condition through operations on similar types. The implicit casting is allowed for types to other types with weaker pre-conditions.