Compile-time check of conversion from a string?

77 Views Asked by At

Let's have a class Foo which defines a conversion constructor from a string. Depending on the contents of the string, this constructor can succeed (an instance of Foo is created) or fail (an exception is thrown):

class Foo
{
public:
    Foo(const char* s)
    {
        if (<format of s is valid>)
            <create Foo, based on the contents of s>;
        else
            <throw an exception>;
    }

[...]
};

We also have operator==() for comparing a Foo and a string:

bool operator==(const Foo& foo1, const char* s)
{
    // s is converted to a Foo, after which the two instances of Foo are compared
}

Client code presumably calls the comparison operator most often with valid string literals:

if (myFoo == "<some valid string literal for building a Foo>") // A - normal case
    [...]

but sometimes it may call the comparison operator with an invalid string literal (programmer's mistake):

if (myFoo == "<some invalid string literal for building a Foo>") // B - abnormal case, throws an exception
    [...]

Is there a way to detect case B at compile-time instead of run-time? (I hope there is, but fear there isn't...)

Note: The validity of the string could be checked, for example, with a regular expression.

0

There are 0 best solutions below