某些东西可以绑定到非常量引用但不能绑定到常量引用的情况?

A case where something could bind to a non-const ref but not to a const ref?

最少的问题

请考虑以下功能:

class NonTrivialClass { /* ... */ };

void f1(NonTrivialClass      &) {}
void f2(NonTrivialClass const&) {}

是否存在调用 f1 的表达式,其中不能将 f1 替换为 f2

上下文

在求职的前景中,我被要求“编写方法double approx(vector<Point>& pts)Point 给出)它使用来自 pts 的点以类似 Buffon 的方式逼近已知常数。

我写了一个定义 double approx(vector<Point> const& pts) 的实现(注意 const)。由于尚未确定的原因,我没有通过测试!

在删除了所有可能的解释后,我对测试平台和那个扣人心弦的 const 限定词产生了怀疑......他们的测试程序是否有可能与 double approx(vector<Point>& pts) 一起工作但是不是 double approx(vector<Point> const& pts)?

如果有这样的表达式(除了 f2 由于任何原因无法访问的情况),那将完全破坏我自己的 C++ 知识...

我认为您更有可能在您的函数中实现了一个最小的错误(您还没有意识到)导致失败;但是,不能排除测试评估软件非常愚蠢,只是为了寻找修复程序,给定签名,无论您的软件是否兼容...

如果您的问题承认疯狂的答案:

struct NonTrivialClass {};
struct NonTrivialClass2 {
    operator NonTrivialClass&();
    operator NonTrivialClass const&();
};

void f1(NonTrivialClass      &) {}
void f2(NonTrivialClass const&) {}

int main()
{
  NonTrivialClass2 foo;

  f1(foo);
  f2(foo); // error: reference initialization is ambiguous
}

当然,这不适用于 vector<> 情况(除非测试机器通过了某种 'tester' 带有损坏(可能是模板化,sfinae-unfriendly-whatever)转换的对象一些包装向量成员的运算符?似乎不合理......但并非不可能)