【问题标题】:Declaring lambda function with auto in a C++ class在 C++ 类中使用 auto 声明 lambda 函数
【发布时间】:2021-12-20 14:57:10
【问题描述】:

是否可以使用auto 在 C++ 类中声明 lambda 函数?我收到编译错误:

错误:“const Temp::(lambda at a.cpp:8:29)”类型的静态数据成员的类内初始化程序需要“constexpr”说明符

我正在为作为类成员变量的集合定义自定义排序函数,并且我想在类中定义此排序函数。我该如何解决这个问题?

其次,即使我将 lambda 函数行移到类之外,我在声明集合的行也会收到错误:

错误:未知类型名称“cmp”

为什么以及如何解决?

class Temp {
public:
    static const auto cmp = [](int p1, int p2)
        {
            return p1>p2;
        };
    set<int, decltype(cmp) > sortedSet(cmp);
    Temp() {
    }
}

【问题讨论】:

  • 半相关:为什么要在这里使用lambda表达式?常规函数会更容易编写(也更短)
  • 按照它的建议使用'constexpr'说明符怎么样?
  • @appleapple 这也不起作用。它抛出 error: unknown type name 'cmp'
  • sortedSet(cmp) 也应该是sortedSet{cmp}
  • @UnholySheep 那是另一个问题。现在可以了。

标签: c++ class auto


【解决方案1】:
  • 按照编译器的建议使用constexpr
  • std::set&lt;int, decltype(cmp)&gt; sortedSet(cmp) 被解析为函数
    • 点赞int sortedSet(int);
#include <set>
class Temp {
public:
    static constexpr auto cmp = [](int p1, int p2)  // <-- use constexpr
        {
            return p1>p2;
        };
    std::set<int, decltype(cmp) > sortedSet{cmp}; // <-- use uniform initialization
    Temp() {
    }
};

或者你也可以用普通功能来做

#include <set>
class Temp {
public:
    static bool cmp(int p1, int p2) {
        return p1>p2;
    };
    std::set<int, decltype(&cmp) > sortedSet{cmp};
    Temp() {
    }
};

【讨论】:

  • 谢谢。我确实尝试过,但得到 error: unknown type name 'cmp'。问题在于使用 sortedSet(cmp) 而不是 sortedSet{cmp}。
  • @apple apple 为什么 sortedSet(cmp) 在正常情况下工作,但在这里不行。为什么要使用 {} 而不是 () ?
  • @flexter () 在类范围内初始化成员时永远不会起作用。大概是因为编译器无法将它与成员函数声明区分开来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-04
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多