#include <cstddef>
struct foo
{
int operator[](size_t i) const { return 1; }
operator char() const { return 'a'; }
};
int main()
{
foo f;
f["hello"]; // compilation error desired here
}
从中提取代码的类确实需要隐式转换和运算符[]
。那么,有没有一种方法可以在不明确转换的情况下防止这种行为呢?
行编译的原因是,通过隐式转换,它可以被重新解释为'a'[“hello”];
,这又与编写*(('a')+(“hello”))相同;
也进行编译。
标准摘录:
5.2.1订阅:
struct foo
{
operator char() const { return 'a'; }
int operator[](size_t i) const { return 1; }
// prevent accidental use of foo["hello"]
int operator[](char const*) const = delete;
};