我想知道编译器如何处理lambda函数而不是常规函数.即使不包括捕获列表,正如我认为的那样,它似乎表现得略有不同.
例如,正如我在上一篇文章中所使用的那样,尝试传递constexpr lambda并使用它来显式指定返回类型,我使用了constexpr lambda并将其作为常规函数参数传递.我引用了部分答案.
constexpr函数的参数本身不是constexpr对象 - 因此您不能在常量表达式中使用它们.
template <typename Lambda_T>
constexpr static auto foo(Lambda_T l) {
return std::array<event, (l())>{};
}
// Compiles with GCC (C++17), though ill-formed (according to the answer of my last post)
Run Code Online (Sandbox Code Playgroud)
虽然,引起我的注意的是,它确实编译了传递constexpr lambda,但是没有编译通过constexpr常规(全局)函数.是什么导致这种差异?编译器在常规函数和lambda函数之间是否存在其他行为差异?
编辑:Lambda实现的示例
foo([](){ return 4; }); // C++17 Lambda's are implicitly constexpr
Run Code Online (Sandbox Code Playgroud)
在这种情况下,lambda基本上是值的包装器.
编辑:全局功能
每当传递一个全局函数时,编译器会抱怨 - 而不是使用lambda - 该函数,无论是否定义为constexpr,都不能在常量条件下使用:
prog.cc:8:20: error: 'l' is not a constant expression
Run Code Online (Sandbox Code Playgroud) 我试图比较a const iterator和a,non-const iterator但不确定它是否正常,所以我查了一下.由于隐式转换为non-const iterator,我发现它没问题const iterator.但是,我想知道您是否应该不要比较这些迭代器,以避免这种转换.例如,
begin_iterator = buf.begin(); end_iterator = buf.cend();
for (; begin_iterator != end_iterator; ++begin_iterator) { ... }
Run Code Online (Sandbox Code Playgroud)
通常,我会认为这是正常的,因为const意味着只读,这很好.但是,我不确定(不必要的)转换.