如何确保 lambda 的自动参数属于同一类型?

How to ensure auto parameters of a lambda are of the same type?

如果我有 lambda 函数

auto foo = [](auto && a, auto && b){ /* some random c++ code */ };

如何声明 ab 应该是同一类型,即使该类型可以是任何类型?

您可以在 lambda 正文中添加一个 static_assert

#include <type_traits>

auto foo = [](auto && a, auto && b){
    static_assert(std::is_same<typename std::remove_reference<decltype(a)>::type,
            typename std::remove_reference<decltype(b)>::type>::value, 
            "Must be of the same type!");
};

您可能想要调整实例化的类型 std::is_same,例如比较等时不考虑 const- 或 volatile 限定符(想想 std::decay)。但注意可能会出现如下问题:

foo("abc", "de"); // fails to compile

因为这里推导的类型是字符数组,而不是const char*

我知道它标有 C++14,但这里有一个 C++20 解决方案以防万一:

auto foo = []<typename T>(T && a, T && b){ /* some random c++ code */ };