继承函数的重载分辨率

Lcd*_*Drm 56 c++ lambda inheritance templates overloading

我希望有一个结构,它接受任意数量的lambda,并作为所有调用运算符的中心调用点.

如果使用与构造中给出的任何lambda都不匹配的参数列表调用调用运算符,则应调用默认调用运算符.

我认为以下代码将完成这一点.每个lambda的调用操作符都被"提升"到Poc类中using.

template <typename ...Lambdas>
struct Poc : Lambdas...
{
    using Lambdas::operator() ...; // Lift the lambda operators into the class

    template <typename ...Ts>
    auto operator() (Ts...)
    {
        std::cout << "general call" << std::endl;
    }
};

// Deduction guide
template <typename ...Ts>
Poc(Ts... ts)->Poc<Ts...>;

int main()
{
    auto l_int = [](int) {std::cout << "int" << std::endl; };

    Poc poc{l_int};
    poc(1);//calls the default operator. why?

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我在结构中没有默认的调用操作符时,一切都按预期工作(使用有效的参数列表).如果我将它添加到结构中(如上面的代码中所示),每次调用默认运算符,无论我调用哪个参数.

根据我的理解,lambda-call-operators和structs(默认)call-operator存在于同一范围内.因此,他们都应该考虑重载决议.由于lamdba运算符比通用默认运算符更具体,因此应该选择它.

显然事实并非如此.这是为什么?

我测试了Microsoft Visual C++,ClangGCC(所有版本均为最新版本).

编辑:

Que*_*tin 43

当你发现它时很简单:你的运算符const不合格,而lambda的运算符是(除非你将lambda定义为mutable).因此,它更适合您的非const实例Poc.

只需添加缺失const:

auto operator() (Ts...) const
Run Code Online (Sandbox Code Playgroud)

  • [就像非成员重载决议一样](http://coliru.stacked-crooked.com/a/266b0b6438be8315) (6认同)
  • @NathanOliver是的,这构成了`this`的隐式转换,它将非模板运算符降低.请原谅我,如果我不通过重载决议标准进行探索,并保持我的"只是平等地限定一切,一切都会很好"的立场;) (5认同)