C++ 重载模式 : call resolution with mutable lambda

标签 c++ c++17

考虑到这个众所周知的 C++ 模式:

template <class... Ts> struct overload : Ts... { using Ts::operator()...; };
template <class... Ts> overload(Ts...) -> overload<Ts...>; // clang needs this deduction guide,
                                                           // even in C++20 for some reasons ...
不知道为什么将参数之一声明为可变 lambda 会更改覆盖分辨率。
实例here on godbolt :
#include <iostream>

template <class... Ts> struct overload : Ts... { using Ts::operator()...; };
template <class... Ts> overload(Ts...) -> overload<Ts...>; // clang needs this deduction guide,
                                                           // even in C++20 for some reasons ...

auto main() -> int
{
    auto functor_1 = overload{
        [](int &&){
            std::cout << "int\n";
        },
        [](auto &&) {   // making this lambda `mutable` makes deduction mismatch ?
            std::cout << "smthg else\n";
        }
    };
    functor_1(42); // prints `int`

    auto functor_2 = overload{
        [](int &&){
            std::cout << "int\n";
        },
        [](auto &&) mutable {
            std::cout << "smthg else\n";
        }
    };
    functor_2(42); // prints `smth else`
}

最佳答案

auto functor = overload{
    [](int &&){
        std::cout << "int\n";
    },
    [](auto &&) {
        std::cout << "smthg else\n";
    }
};
functor(42); // prints `int`
两个闭包都有const合格 operator()就是这样 int&&是更好的匹配,因为它不是模板。
auto functor = overload{
    [](int &&){
        std::cout << "int\n";
    },
    [](auto &&) mutable {
        std::cout << "smthg else\n";
    }
};
functor(42); // prints `smthg else`
您的 auto&&关闭不是const不再合格,意味着没有 const为了调用它需要发生的资格调整。这使得重载成为身份完全匹配,而 int&&过载需要 const资格调整。身份完全匹配胜过const资格调整精确匹配每[tab:over.ics.scs]所以这就是为什么你会看到 auto&&版本称为。

关于C++ 重载模式 : call resolution with mutable lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66890356/

相关文章:

c++ - 传递指向结构的引用作为模板参数

c++ - 我们可以使用单个指针实现双向链表吗?

c++ - 为什么for_each通过move返回函数

c++ - 使用函数模板重载运算符

c++ - 什么是 'auto my_var =' 与 'auto& my_var =' 的通信?

c++ - 用说明符extern声明的C++中的标识符链接

c++ - 无法从 initializer_list 转换为我的类型,该类型具有模板化可变参数构造函数

c++ - 迭代 C++ 列表中一对(或元组)的特定项

c++ - 将 YUY2 转换为 YV12

c++ - 创建虚拟共享对象 (.so) 以依赖于其他共享对象