如何解决从字符串转换的编译时检查?
让我们有一个 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 举报,一经查实,本站将立刻删除。