Kaleb Barrett
Kaleb Barrett

Reputation: 1595

Implicit casting limitations

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.

Upvotes: 1

Views: 155

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

Unlike standard conversions, implicit conversion sequence can consist of one user-defined conversion at most.

Implicit conversion sequence consists of the following, in this order:

1) zero or one standard conversion sequence;

2) zero or one user-defined conversion;

3) zero or one standard conversion sequence.

For your 1st code snippet, given B("example");, two user-defined conversions are required; const char* to std::string and std::string to A.

As the workaround, you can add another conversion constructor as you tried, or add explicit conversion to construct B, e.g.

B(A("example"));

Upvotes: 4

To realize an implicit cast you must put the data type between parentheses, followed by the variable(int)(var)

Upvotes: -2

Related Questions