从字符串转换的编译时检查?

问题描述

让我们有一个 Foo 类,它定义了一个字符串的转换构造函数。根据字符串的内容,此构造函数可以成功(创建 Foo 的实例)或失败(抛出异常):

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>;
    }

[...]
};

我们还有 operator==() 用于比较 Foo 和字符串:

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

客户端代码可能最常使用有效的字符串文字调用比较运算符:

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

但有时它可能会使用无效的字符串文字调用比较运算符(程序员的错误):

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

有没有办法在编译时而不是运行时检测案例 B? (我希望有,但担心没有...)

注意:可以检查字符串的有效性,例如,使用正则表达式。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...