[英]C++ Defining a (static) lambda function inside a class
這是我的問題的起點。 一些無法編譯的代碼。
class MyClass
{
// for sorting
auto lambda = [](const auto& x, const auto& y)
{
return x.x < y.x;
};
// something that needs a custom way to sort
std::set<SomeOtherClass, lambda> mySet;
};
編譯器產生的錯誤是
error: non-static data member declared with placeholder ‘auto’
auto databaseSortLambda = +[](const auto& x, const auto &y)
它看起來像一個簡單的修復。 將static
放在某處。 My understanding is that this won't work, because this defines a static variable called lambda
which has the type "closure object", rather than the lambda function itself being a static function.
class MyClass
{
// for sorting
static auto lambda = [](const auto& x, const auto& y)
{
return x.x < y.x;
};
// something that needs a custom way to sort
std::set<SomeOtherClass, lambda> mySet;
};
這會產生以下編譯器錯誤:
error: ‘constexpr’ needed for in-class initialization of static data member ‘MyClass::<lambda(const auto:1&, const auto:2&)> MyClass::lambda’ of non-integral type
問題是為什么? 我對constexpr
的理解是它告訴編譯器它應該計算表達式的結果,並使用它而不是在運行時計算表達式。
在這種情況下,這個 lambda 怎么可能是constexpr
? 當然,直到運行時才能知道xx < yx
的值?
此時編譯器是否只是告訴我一些毫無意義的事情? 有沒有辦法將我的 lambda 寫為 class 內的“靜態函數”?
當有人說 lambda 是constexpr
時,可能意味着兩件事。
lambda表達式本身可能有一個constexpr
限定符。 這確定了從 lambda 表達式生成的閉包類型的operator()
是否是constexpr
限定的(盡管如果operator()
滿足 function (模板)為constexpr
的要求,即使沒有該說明符,它也將是constexpr
限定的-合格的)。
另一個是您存儲 lambda 的變量是constexpr
-qualified。 這與閉包類型的operator()
或等效的主體無關。 相反,它確定 lambda object 本身是否為const
並由常量表達式初始化。
沒有任何捕獲的 lambda 不需要執行任何初始化操作。 lambda 表達式本身可以在常量表達式中使用(C++17 起),因此沒有什么可以使初始化程序成為常量表達式:
// for sorting
constexpr static auto lambda = [](const auto& x, const auto& y)
{
return x.x < y.x;
};
或者, inline
也可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.