重载具有相同要求条件的函数

Overloading a function with the same require conditions

以下代码(online)

template<int m> struct A {
    void f(A<m> const& that) const requires m > 1 { }
    void f(A<1> const& that) const requires m > 1 { }
};

int main(){
    A<2> a;
    a.f(a);
    return 1;
}

给出错误 void A<m>::f(const A<1>&) const requires m > 1 [with int m = 1] cannot be overloaded with void A<m>::f(const A<m>&) const requires m > 1 [with int m = 1]

为什么不允许这样做?

这里的关键是“[with int m = 1]”。当m为1时,得到这两个"overloads"

void f(A<1> const& that) const requires 1 > 1 { }
void f(A<1> const& that) const requires 1 > 1 { }

未满足的 require 子句不会 "undeclare" 重载。它只是让重载不参与重载决议。重载仍然被声明,在你的情况下,你得到了 m = 1.

两次完全相同的定义

一个简单的解决方法是使签名不同,从而获得两个重载

void f(A<m> const& that) const requires m > 1 { }
void f(A<1> const& that, int = 0) const requires m > 1 { }